我已经审查了很多有关此类问题的答案,但现在我对最佳方法感到困惑。鉴于最新的jquery,我想
在调用函数(doAjax)中,如何等待回调,然后完成对成功或错误的处理(在这种情况下,成功时清除表格,错误时保持原样)
感谢任何建议,
Art [EDIT] 你们发现有一个错字,打电话应该是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 } });