我正在使用 javascript 和 AJAX。我打电话给服务器进行登录。它发送一个登录是真的响应。然后我需要通过再次调用服务器来收集有关用户的所有信息。如果我立即拨打电话,服务器将返回用户未登录的响应。我可以使用 setTimeout(myFunction(), 1000) 或 setInterval(myFunction(), 1000); 拨打第二个电话。我想知道,是否有一种干净的方法可以在不运行其余代码的情况下继续等待正确的响应?我想我最大的问题是,如果不将所有内容都放入回调响应中,我怎么能做到这一点?我希望代码有点模块化。
问问题
41 次
1 回答
1
您需要使用异步技术进行编程。jQuery 中的典型 Ajax 调用然后处理响应如下所示:
$.ajax(...).then(function(result) {
// put code here that uses the result
// then continue on with other code that should run after the result was processed
});
// code here will run BEFORE the ajax call completes
如果您想运行一个 ajax 调用,然后再运行另一个,您可以将它们链接起来,也可以从第一个的完成回调中运行第二个:
$.ajax(...).then(function(result) {
// process result of the first
// run second ajax call
return $.ajax(...)
}).then(function(secondResult) {
// code here when second ajax call is done
});
于 2015-01-16T17:03:19.357 回答