admin管理员组

文章数量:1425749

So I am posting a call to a method that just returns a string and my post request returns an object with a string in the responseText field, but the d.responseText returns "undefined." Anyone know why? I thought it was because it was AJAX but why is does the var d have the correct value?

var d = $.post("/home/status_update", function(data) {return data});
console.log(d);
console.log(d.responseText);

So I am posting a call to a method that just returns a string and my post request returns an object with a string in the responseText field, but the d.responseText returns "undefined." Anyone know why? I thought it was because it was AJAX but why is does the var d have the correct value?

var d = $.post("/home/status_update", function(data) {return data});
console.log(d);
console.log(d.responseText);
Share Improve this question asked Jun 21, 2012 at 20:25 blcblc 1612 silver badges9 bronze badges 1
  • 2 api.jquery./jquery.post – user1106925 Commented Jun 21, 2012 at 20:28
Add a ment  | 

2 Answers 2

Reset to default 5

$.post returns a promise object, try using it.

var d = $.post("/home/status_update");
d.done(function(data) {
    console.log(data);
});

It's one of the far most mon errors I'm finding here on AJAX requests: many people don't realize that AJAX is *A*synchronous, you can't expect that your d variable gets valued because the code continues its execution regardless of the pletion of the AJAX request.

You can use the retrieved value only when the request-response roundtrip has been pleted.

What you have to do is to actually use the returned value inside the function(data), because you are guaranteed that it will be executed only after the value is actually retrieved.

The other user obtains the same thing by binding the done event, that is fired upon the pletion of the AJAX request/response. It's the same thing coded in a slight different manner. The shorthand is:

var d = $.post("/home/status_update", function(data) {console.log(data);});

Bear in mind that, as a general application architecture, with AJAX requests you cannot expect to use a single function, you will define functions that will manupulate your response upon every AJAX pletion. Try to think your application in a more "fragmented" way.

本文标签: javascriptJS object returned but responseText doesnt workStack Overflow