我正在开发 Cordova 混合移动应用程序。我正在调用 API 将数据加载到我的变量中并进行处理。下面是问题所在。
首先,我使用 ajax 调用 API。 ajax 调用后,我检查 jsonString 是否为空,如果是,则重新加载页面以再次运行 ajax 调用。
$.ajax({
url: GetConfigUrl // working URL,
type: 'POST',
data: {
token: '123456'
},
cache: false,
datatype: 'json',
contenttype: "application/json",
success: function (data, response, xhr) {
debugger
jsonString = data.Value;
},
error: function (data) {
// do nothing
)
});
if (jsonString == '') {
// Display popup to ask user the reload the page
}
return true;
我在成功调用函数中有一个调试器,但是它没有命中,直接去检查jsonString是否为空,之所以为空是因为它没有调用ajax加载数据并继续显示弹出窗口来询问用户重新加载页面。
点击页面重新加载后,成功调用中的调试器将被点击并能够检索该值。因此 jsonString 不为空并且能够继续。
似乎第一个调用已发出,但始终处于待处理状态。第二次调用成功并返回正确的值。这样jsonString检查就通过了。
当第一个 ajax 调用不成功且处于挂起状态,但所有后续调用都成功时,此问题始终会发生。
那么这里可能出了什么问题呢?如何保证第一次ajax调用成功并始终返回数据?
最佳答案
Ajax 是异步执行的,将逻辑放在 success 函数中,以便在 ajax 调用完成时执行
$.ajax({
url: GetConfigUrl // working URL,
type: 'POST',
data: {
token: '123456'
},
cache: false,
datatype: 'json',
contenttype: "application/json",
success: function (data, response, xhr) {
debugger
jsonString = data.Value;
if (jsonString == '') {
// Display popup to ask user the reload the page
}
},
error: function (data) {
// do nothing
)
});
return true;
关于javascript - Ajax调用一开始不起作用,后来调用成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38494558/