在嵌套的 ajax 调用中获取 JSON
Getting JSON in nested ajax calls
发送给某些 'request_url' returns json 格式响应的 http 请求 {'succes': 1, 'html': 'thestuff'}
所以当
jQuery.ajax({
url: 'request_url',
success: function(response){
alert(response.html); //'thestuff' is here as expected
}
});
'thestuff' 可以按预期在 response.html 中找到。但是,如果此 ajax 在另一个 ajax 请求的 'success' 回调中被调用,那么 response.html 将变为空并且 'thestuff' 将变为 'response'.
jQuery.ajax({
url: 'some_other_url',
success: function(some_other_response){
jQuery.ajax({
url: 'request_url',
success: function(respose){
alert(response.html); //there is nothing
alert(response); //I see 'thestuff' which is expected in 'html'
}
})
}
});
为什么会这样?
更新:'thestuff' 包含一些带有 {} 的 js 代码我想有些东西可能会混淆,但为什么它适用于单个(未嵌套)ajax 请求。
信誉不足,无法发表评论,因此添加为答案
这里扩展了 charlietfl 对使用 dataType 的评论。
我使用 dataType="json" 使其工作。 Json 必须按照 jQuery 文档严格格式化。
jQuery.ajax({
url: 'some_other_url',
success: function(some_other_response){
jQuery.ajax({
url: 'request_url',
dataType:"json",
success: function(response){
alert(response.status); //there is nothing
alert(response); //I see 'thestuff' which is expected in 'html'
}
})
}
});
request_url 应该 return 像这样(注意,应该使用引号而不是撇号)
{"status":"s","html":"some stuff"}
发送给某些 'request_url' returns json 格式响应的 http 请求 {'succes': 1, 'html': 'thestuff'}
所以当
jQuery.ajax({
url: 'request_url',
success: function(response){
alert(response.html); //'thestuff' is here as expected
}
});
'thestuff' 可以按预期在 response.html 中找到。但是,如果此 ajax 在另一个 ajax 请求的 'success' 回调中被调用,那么 response.html 将变为空并且 'thestuff' 将变为 'response'.
jQuery.ajax({
url: 'some_other_url',
success: function(some_other_response){
jQuery.ajax({
url: 'request_url',
success: function(respose){
alert(response.html); //there is nothing
alert(response); //I see 'thestuff' which is expected in 'html'
}
})
}
});
为什么会这样?
更新:'thestuff' 包含一些带有 {} 的 js 代码我想有些东西可能会混淆,但为什么它适用于单个(未嵌套)ajax 请求。
信誉不足,无法发表评论,因此添加为答案 这里扩展了 charlietfl 对使用 dataType 的评论。
我使用 dataType="json" 使其工作。 Json 必须按照 jQuery 文档严格格式化。
jQuery.ajax({
url: 'some_other_url',
success: function(some_other_response){
jQuery.ajax({
url: 'request_url',
dataType:"json",
success: function(response){
alert(response.status); //there is nothing
alert(response); //I see 'thestuff' which is expected in 'html'
}
})
}
});
request_url 应该 return 像这样(注意,应该使用引号而不是撇号)
{"status":"s","html":"some stuff"}