我想通过jQuery.ajax()
获取一些数据,通过success保存这些数据,然后使用它。函数的顺序为:
$.ajax({
url: this.html_url,
cache: false,
success: function(data){
//Here the data is saved via HTML5 localStorage
}
});
doSomething();//The stored data is used in this function.
问题是在成功函数保存下载的数据之前调用doSomething()
。因此,数据甚至在保存之前就已经被使用了。有人能帮上忙吗?
发布于 2012-01-20 18:50:21
这是因为ajax
调用是通过asynch
实现的。通过default
在ajax调用中设置async : false
,它是true
。
$.ajax({
url: this.html_url,
cache: false,
async : false, // added this
success: function(data){
//Here the data is saved via HTML5 localStorage
}
});
在success
中调用doSomething
的第二种方法
success: function(data){
//Here the data is saved via HTML5 localStorage
doSomething()'
}
发布于 2012-01-20 18:49:51
假设我明白你的意思。为什么不在success
回调中调用doSomething()
呢?
$.ajax({
url: this.html_url,
cache: false,
success: function(data){
//Here the data is saved via HTML5 localStorage
doSomething();//The stored data is used in this function.
}
});
发布于 2012-01-20 18:51:13
这是因为AJAX调用是异步的。这意味着您的脚本不会等待它们完成后再继续(很像setTimeout()
)。
只需在成功回调中包含doSomething()
函数即可。
https://stackoverflow.com/questions/8946338
复制