javascript - JS object returned but responseText doesnt work - Stack Overflow

So I am posting a call to a method that just returns a string and my post request returns an object wit

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745351474a4623859.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信