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
2 Answers
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
版权声明:本文标题:javascript - JS object returned but responseText doesnt work - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745351473a2654794.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论