Javascript ajaxjquery同步回调成功
我有一个函数,可以调用ajax。我在最后一段代码注释中描述了这个问题Javascript ajaxjquery同步回调成功,javascript,jquery,ajax,synchronous,Javascript,Jquery,Ajax,Synchronous,我有一个函数,可以调用ajax。我在最后一段代码注释中描述了这个问题 function doop(){ var that = this; var theold = "theold"; var thenew = "thenew"; $.ajax({ url: 'doop.php', type: 'POST',
function doop(){
var that = this;
var theold = "theold";
var thenew = "thenew";
$.ajax({
url: 'doop.php',
type: 'POST',
data: 'before=' + theold + '&after=' + thenew,
success: function(resp) {
if(resp == 1) {
$(that).siblings('.theold').html(thenew);
}
}
});
// I have some code here (out of the ajax) that **further** changes
// the .theold's html beyond what it was changed inside ajax success
// but the change depends on whether the resp (inside the success
// function) returned 1 or not, so this code out here depends on the ajax
// so it looks like I have to turn this ajax call into a sync ajax
return false;
}
根据代码注释中描述的问题,什么更改最适合这种情况?您需要为以下同步请求设置async:false:
function doop(){
var that = this;
var theold = $(this).siblings('.theold').html();
var thenew = $(this).siblings('.thenew').val();
$.ajax({
async: false,
url: 'doop.php',
type: 'POST',
data: 'before=' + theold + '&after=' + thenew,
success: function(resp) {
if(resp == 1) {
$(that).siblings('.theold').html(thenew);
}
}
});
// some other code
return false;
}
getData(function(data){
console.log(data); //do something
});
有关详细信息,请参见如stefita所指出的,将Ajax调用设置为synchronous,或者将代码移到成功回调中。你为什么不能这样做?即使是另一个Ajax调用,仍然可以完成—您可以嵌套它们。到目前为止,根据您提供的信息(我看不到有问题的代码,也没有足够的项目领域知识),我真的看不到问题。我更喜欢使用回调来完成这项工作,因为它实现了完全相同的结果,而实际上没有使其同步。我使用success:callback,然后将回调作为参数传入
function getData(callback) {
$.ajax({
url: 'register/getData',
data: "",
dataType: 'json',
success: callback
});
}
然后我这样调用这个函数:
function doop(){
var that = this;
var theold = $(this).siblings('.theold').html();
var thenew = $(this).siblings('.thenew').val();
$.ajax({
async: false,
url: 'doop.php',
type: 'POST',
data: 'before=' + theold + '&after=' + thenew,
success: function(resp) {
if(resp == 1) {
$(that).siblings('.theold').html(thenew);
}
}
});
// some other code
return false;
}
getData(function(data){
console.log(data); //do something
});
我一直读到设置
async:false
不好,而回调
更好。但我怀疑它是否如此简单。根据我更新的问题,你推荐哪一个?嗯,实际上你为success属性声明的函数是回调函数。顺便说一句,我刚才看到您正在将结果与整数进行比较,但我非常确定您在默认情况下得到的是文本,因此它应该是resp==“1”
。您可以在ajax请求之外的某个地方定义回调函数。可能你看到的就是一个回调函数,实际上,你是对的,我得到了文本,1只是一个例子。当我在这里发布代码时,我会尽量简化代码,以使人们能够更友好地阅读;)@stefita:我明白了,所以他可能没有success:function(resp)
,而是在ajax之外的某个地方定义了success:callback
。听起来不错,我想我应该找到正确的答案了。谢谢你的帮助。我明白了,所以$(.ajax)调用可以嵌套。听起来不错,我试试看效果如何。