【发布时间】:2014-01-29 21:32:54
【问题描述】:
我写了这个对象并将它运行到我拥有的页面中:
var dataPage = {
getData: function() {
return $.ajax({
url: '/my_url/',
data: {
product: 'some_product',
state: 'some_state'
},
type: 'POST',
async: true,
success: function (data) {
//console.log(data);
dataPage.results = data;
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Error:' + xhr.status);
alert(thrownError);
}
});
}
,returnData: function(){
var xhr = this.getData();
//console.log(xhr);
xhr.done(function() {
//console.log(xhr.responseText);
this.results = xhr.responseText;
$('#JSON').html(this.results);
});
}
}
var results = dataPage.returnData()
console.log(results)
当属性async 设置为false 时,它可以完美运行:数据通过id="JSON" 加载到div。两个console.log()s 返回数据,一切正常。
现在我想切换到async: true,但我不知道如何应用闭包来使函数正确传递结果数据,避免xhr.responseText 成为undefined,因为getData() 来电。
已编辑
我编辑了上面的代码,添加了returnData()函数,但是最后一个console.log()仍然返回undefined。添加.done() 并没有解决取出到全局范围结果如果async: true...
【问题讨论】:
-
只需将
$('#JSON').html(jqXHR.responseText);移动到您确定ajax 请求已经完成的地方。 -
你能说得更准确点吗?
-
当然,请参阅 JasonP 的回答。
标签: javascript jquery ajax closures