2011-05-26 62 views
2

使用这样如何使用本地.json文件和jQuery获取json对象的Ajax响应?

$.ajax({ 
url: 'mydata.json', 
type: 'get', 
error: function(data){ 
}, 
success: function(data){ 
    data=jQuery.parseJSON(data); 
    //do something with data    
    } 
}); 

它工作时,我实现它与服务器的URL,其内部生成JSON响应对象并返回服务器,除了完美的jQuery Ajax请求。那么我不需要jQuery.parseJSON(数据)。有没有一种方法可以使用本地json文件并获得响应作为json对象?

回答

0

我建议检查一下,看看返回的数据是否已经转换为JSON对象。如果是这样,那么没有理由解析它。

$.ajax({ 
     url: 'mydata.json', 
     type: 'get', 
     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 
     } 
    }); 
0

这是一个已知问题是success()回调将不会触发本地jQuery.ajax。如果您打算在本地运行脚本,请改用complete()。也正因为这个问题,你不应该使用jQuery.getJSON作业(因为该函数将仅当成功。)

3
$.ajax({ 
url: 'mydata.json', 
type: 'get', 
dataType: 'json', 
error: function(data){ 
}, 
success: function(data){ 
    //do something with data    
    } 
}); 

指定dataType: 'json'告诉jQuery的期待JSON数据,并自动解析它。

0
$.getJSON('mydata.json').done(function(response) { 
    console.log("Success"); 
}).fail(function() { 
    console.log("Error"); 
});