Javascript ajax请求中丢失的变量
在尝试将变量作为参数传递给嵌套ajax请求回调时,我遇到了一个奇怪的行为:Javascript ajax请求中丢失的变量,javascript,jquery,ajax,Javascript,Jquery,Ajax,在尝试将变量作为参数传递给嵌套ajax请求回调时,我遇到了一个奇怪的行为: $('form').on('submit',function(e){ $.ajaxSetup({ header:$('meta[name="_token"]').attr('content') }) e.preventDefault(e); $.ajax({ type:"POST", url:dest_url, data:$(
$('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 done回调中,我的变量似乎被解除,console.log在控制台中输出我的整个html代码。。。
我从没见过这样的事。您是否解释了为什么以及如何将id作为参数传递给ajax回调?方法的参数是ajax调用的响应。如果您的调用返回一个HTML页面,
id
变量将获得分配给它的所有HTML字符串
要将id保留在其变量中,只需使用另一个变量,如:
.done(function(data) {
console.log(data)
console.log(id);
});
在
done
中传递给函数的第一个参数是来自AJAX请求的响应。无论您如何调用变量,这都是传递给该函数的内容
但是,您可以捕获闭包中的值,只需给它另一个名称并将其分配给局部变量即可。大概是这样的:
done(function(response) {
var theId = id;
// "response" contains the response from the server.
// "theId" contains the value of `id` from outside this function.
})
在没有看到后端代码的情况下,我认为您需要
url:src_url
而不是url:location.href
。否则,我不确定您期望的是什么-您只是对当前页面发出GET请求,并转储返回的内容,这只是您的HTML。@Quasdunk,谢谢,但这是正常的,我使用下面的src_url,但我没有粘贴我的全部代码。我的问题解决了!这是正确的答案!我也可能错了,但你难道不能继续叫它id吗?在op的代码中,id不起作用的唯一原因是,他正在用ajax响应的值有效地覆盖该名称。@Robbie Milejczak是的,我的问题已经解决了,你们都是对的,我在脚本中使用了id,但没有对其产生影响。