gpt4 book ai didi

jquery - 等待来自调用函数的 jquery ajax 回调

转载 作者:行者123 更新时间:2023-12-03 21:51:40 25 4
gpt4 key购买 nike

我已经查看了此类问题的很多答案,现在我对最好的方法感到困惑。鉴于最新的 jquery,我想要

  1. 调用ajax函数
  2. 进行ajax处理(成功或错误)//工作正常
  3. 成功或错误时将状态返回给调用函数以进行进一步处理

在调用函数(doAjax)中,如何等待回调然后完成成功或错误的处理(在本例中,成功时清除表单,错误时保持原样)

感谢您的任何建议,

艺术[编辑]你们发现了一个拼写错误,调用应该是 doAnAjax 而不是 doAjax

$(function () {
doAnAjax(Url, data, function (myRtn) {
if (myRtn == "success") {
resetForm($('#myForm'));
resetForm($('form[name=addChlGrp]'));
} else {
$('.rtnMsg').html("Opps! Ajax Error");
}
});
});

function doAnAjax(newUrl, data) {
$.ajax({
url: newUrl,
async: true,
dataType: 'html',
beforeSend: function () {
$('.rtnMsg').html("<img src=_cssStyleImg_-A-loading.gif>");
},
type: "GET",
data: data,
cache: false,
success: function (data, textStatus, xhr) {
$('.rtnMsg').html(data);
myRtnA = "Success"
return myRtnA;
},
error: function (xhr, textStatus, errorThrown) {
$('.rtnMsg').html("opps: " + textStatus + " : " + errorThrown);
myRtnA = "Error"
return myRtnA;
}
});
}

最佳答案

您必须使用回调函数。请尝试以下操作:

$(function() {

// I think doAjax should doAnAjax()
// here you're passing callback
// but you're not using it doAnAjax()

doAnAjax(Url, data, function(myRtn) {
if (myRtnV == "success") {
resetForm($('#myForm'));
resetForm($('form[name=addChlGrp]'));
} else {
$('.rtnMsg').html("Opps! Ajax Error");
}
});
});

// pass callback as third parameter to doAnAjax()

function doAnAjax(newUrl, data, callBack) {
$.ajax({
url: newUrl,
async: true,
dataType: 'html',
beforeSend: function() {
$('.rtnMsg').html("<img src=_cssStyleImg_-A-loading.gif>");
},
type: "GET",
data: data,
cache: false,
success: function(data, textStatus, xhr) {
$('.rtnMsg').html(data);
myRtnA = "Success"
return callBack( myRtnA ); // return callBack() with myRtna
},
error: function(xhr, textStatus, errorThrown) {
$('.rtnMsg').html("opps: " + textStatus + " : " + errorThrown);
myRtnA = "Error"
return callBack ( myRtnA ); // return callBack() with myRtna
}
});

关于jquery - 等待来自调用函数的 jquery ajax 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11576176/

25 4 0
文章推荐: javascript - 如何检查光标是否位于某个元素上?
文章推荐: javascript - jquery $ ('