如何使用本地.json文件和jquery在ajax响应中获取json对象?

问题描述

| 像这样使用jQuery ajax请求
$.ajax({
url: \'mydata.json\',type: \'get\',error: function(data){
},success: function(data){
  data=jQuery.parseJSON(data);
  //do something with data              
    }
});
除非我在服务器上用内部生成json响应对象并返回的服务器url实施它,否则它的工作原理是完美的。那么我不需要jQuery.parseJSON(data)。有没有一种方法可以使用本地json文件获取响应作为json对象?     

解决方法

$.ajax({
url: \'mydata.json\',type: \'get\',dataType: \'json\',error: function(data){
},success: function(data){
  //do something with data              
    }
});
指定
dataType: \'json\'
告诉jQuery期望JSON数据并自动解析。     ,我建议检查一下返回的数据是否已经转换为JSON对象。如果是这样,则没有理由解析它。
    $.ajax({ 
      url: \'mydata.json\',error: function(data){ },success: function(data){ 
        console.log(data); //check to see if jQuery has already converted the response to a JSON object
        //data=jQuery.parseJSON(data); //do something with data
      }
    });
    ,这是一个已知的问题,在本地jQuery.ajax上不会触发
success()
回调。如果要在本地运行脚本,请改用
complete()
。同样由于这个问题,您不应该为工作使用jQuery.getJSON(因为该函数仅在成功时才会触发。)     ,
$.getJSON(\'mydata.json\').done(function(response) {
    console.log(\"Success\");
}).fail(function() {
    console.log(\"Error\");
});