在嵌套的 ajax 调用中获取 JSON

Getting JSON in nested ajax calls

本文关键字:获取 JSON 调用 ajax 嵌套      更新时间:2023-09-26

发送到某个'request_url'的http请求以格式{'succes': 1, 'html': 'thestuff'}返回json响应

所以当

jQuery.ajax({
   url: 'request_url',
   success: function(response){
      alert(response.html); //'thestuff' is here as expected
   }
});

正如预期的那样.html可以在响应中找到"thestuff"。但是,如果这个 ajax 是在另一个 ajax 请求的"成功"回调中调用的,那么响应.html是空的,而"thestuff"将变为"响应"。

 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请求一起使用。

没有足够的声誉来评论,所以添加为答案这里扩展了使用数据类型的查理特夫尔评论。

我使用 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应该返回这样的东西(注意,应该使用引号而不是撇号)

{"status":"s","html":"some stuff"}