当尝试将变量作为参数传递给嵌套的 ajax 请求回调时,我遇到了奇怪的行为:
$('form').on('submit',function(e){
$.ajaxSetup({
header:$('meta[name="_token"]').attr('content')
})
e.preventDefault(e);
$.ajax({
type:"POST",
url:dest_url,
data:$(this).serialize(),
dataType: 'json',
success: function(data){
if($.isEmptyObject(data.error)){
// performing some actions
// at this point, data.id contains my id
// We call an other function,
// which performs an other ajax request,
// with data.id as parameter
listRefresh(data.id);
}else{
// error message
}
},
error: function(data){
// error message
}
})
});
function listRefresh(id){
console.log(id); // At this point, id contains my id
$.ajaxSetup({
header:$('meta[name="_token"]').attr('content')
})
var src_url = location.href + '?id='+id;
$.ajax({
url: location.href,
type: 'GET',
cache: false
})
.done(function(id) {
console.log(id);
// At this point the console outputs
// all my html code in place of id
// I tried to pass data, response, id, but still the same issue
})
.fail(function() {
//error message
});
}
正如上面的代码注释中所述,在 listRefresh ajax did 回调中,我的变量似乎消失了,console.log 在控制台中输出了我的整个 html 代码...
我从来没有见过这样的事情。你有解释为什么吗?我如何将我的 id 作为参数传递给 ajax 回调?
传递给函数的第一个参数done
是 AJAX 请求的响应。你做什么并不重要call变量,这就是将传递给该函数的变量。
但是,您可以捕获闭包中的值,只需给它另一个名称并将其分配给局部变量即可。像这样的事情:
done(function(response) {
var theId = id;
// "response" contains the response from the server.
// "theId" contains the value of `id` from outside this function.
})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)