当我使用 jquery.when 使用母版页在 Web 表单中运行时遇到一些问题
这是我使用母版页的 Web 表单代码
$(document).ready(function(){
$.when(masterPageFunction()).done(function(){
webFormFunction();
});
})
这是我的母版页
function masterPageFunction() {
//In this function i call 2 ajax like this
$.ajax({
type: "POST",
url: "/api/master/xxx/",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$.ajax({
type: "POST",
url: "/api/master/xxx2/",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
}
})
}
})
}
结果是当母版页功能未完成时网络功能正在运行 请帮忙,非常感谢
最佳答案
您很接近,但是 when
、then
和 done
函数依赖于 promise 。您不会在代码中返回任何 promise ,因此它只是直接运行。
首先,您需要在母版页的 done
函数中获取 promise 完成后的结果。为此,我们将向回调添加一个 response
参数,然后将其传递给 webFormFunction
。
$(document).ready(function(){
$.when(masterPageFunction()).done(function(response){
webFormFunction(response);
});
})
接下来,我们需要向 masterPageFunction
添加一个 promise 并返回它。您使用要发送回母版页中的 done
函数的响应来解决 promise 。像这样:
function masterPageFunction() {
// Create the promise
var deferred = $.Deferred();
//In this function i call 2 ajax like this
$.ajax({
type: "POST",
url: "/api/master/xxx/",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$.ajax({
type: "POST",
url: "/api/master/xxx2/",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
// Resolve the promise with the response from $.ajax
deferred.resolve(response);
}
});
}
});
// Return the promise (It hasn't been resolved yet!)
return deferred.promise();
}
这样,webFormFunction
将不会被调用,直到第二次 ajax 调用完成,即 resolve the promise。
关于c# - jquery $.when 不通过母版页中的等待功能工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50610021/