这些天来,我一直在做一些ajax函数,但是我面临一个小问题.我有一个调用ajax的函数.我想给它一个值,并在请求完成后返回该函数.我怎么做:
>触发ajax子函数的返回
>等待“答案”变量更改,然后将其返回
这是精神(实际上是行不通的):
var answer = null;
$.ajax({
url: "validate/"+id,
type: 'POST',
data: {'field' : value},
success: function(data) {
//noty({text: data, type: 'success'});
},
error:function (xhr, ajaxOptions){
noty({text: xhr.status + " : " + xhr.responseText, type: 'error'});
answer = "error";
}
});
return answer;
谢谢!
解决方法:
您无法从AJAX函数返回值,因为AJAX请求是异步发生的(请考虑检索远程网页需要多长时间).
相反,您需要提供一个回调(在请求完成时执行的函数):
function ajaxFunction(onComplete) {
$.ajax({
url: "validate/"+id,
type: 'POST',
data: {'field' : value},
success: function(data) {
//noty({text: data, type: 'success'});
onComplete(data);
},
error:function (xhr, ajaxOptions){
noty({text: xhr.status + " : " + xhr.responseText, type: 'error'});
onComplete(error);
}
}
}
然后,您将一个函数作为参数传递给ajaxFunction,它将接收来自AJAX请求的响应.
ajaxFunction(function (answer) {
// do something with answer
});
由于需要id和value参数,因此可以将其添加到ajaxFunction方法的参数中.
标签:javascript,jquery
来源: https://codeday.me/bug/20191101/1981771.html