5

在以 JSON 文件的形式获得 HTTP 响应后,如何使用 jQuery 处理其纯内容?

我以前做过,但我现在不知道怎么做。

我正在使用这个函数来检索 JSON 内容。

var json = $.getJSON("test.json",  
   function(response){
           // do stuff
       }
);

当然,我可以处理 JSON 中包含的数据,但我想处理和打印它的纯内容,如下所示:

{"name": "Pepe","age" : "20"}

以下

alert(response);

只是给我[对象对象]

还有这个

alert(jQuery.parseJSON(json));

只是给我空

我似乎无法在任何地方找到答案。我对这一切都很陌生,所以我一定使用了错误的搜索词,因为它看起来是一件微不足道的事情。

4

3 回答 3

9

JSON.stringify可能是你想要的。MDN 文档

于 2012-07-10T19:55:56.467 回答
8

回调$.getJSON实际上有 3 个参数。 data,textStatusjqXHR.

jqXHR对象包含一个responseText包含原始 JSON 字符串的属性。

var json = $.getJSON("test.json",  
   function(response, status, jqXHR){
           // do stuff
           console.log(jqXHR.responseText);
       }
);
于 2012-07-10T20:05:50.433 回答
1

与其使用警报查看输出,不如使用控制台,然后使用 John Resig 的解决方案来记录此类数据?

// usage: log('inside coolFunc',this,arguments);
// http://paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
  log.history = log.history || [];   // store logs to an array for reference
  log.history.push(arguments);
  if(this.console){
    console.log( Array.prototype.slice.call(arguments) );
  }
};

进而:

window.log(response);

取自: http: //paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/

于 2012-07-10T19:54:47.637 回答