2011-06-24 279 views
8

我有以下的jQuery/JS代码为什么parseJSON返回null

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script> 
<script> 
    $.getJSON("http://example/topics", {}, function(data){ 
      console.log(data); // display the JSON *data* in the web console 
      console.log($.parseJSON(data)); 
    }); 
</script> 

的console.log(数据)显示Firebug的控制台内JSON数据(Firefox插件),但的console.log($。 parseJSON(data))显示null

可能是什么原因。

我需要将JSON字符串转换为数组。

回答

21

我假设是因为$.getJSON已经解析过数据。 data是Javascript对象。

success的回调被传递返回的数据,其通常是JavaScript对象或阵列由JSON结构所定义和使用$.parseJSON()方法解析。

当然,如果您向我们显示输出,我们可以说更多,但通常,$.getJSON已经解析了响应。

P.S .:我希望你在你的真实代码中使用正确的URL。