2012-08-31 143 views
0

我想解析一个字符串是一个JSON字符串的响应。在我的网络应用程序的另一页下面的​​代码工作正常。但它并不适用于我正在处理的当前页面。以下是代码:为什么我不能使用jQuery.parseJSON(json)解析json字符串?

$.ajax({ 
    type: 'POST', 
    url: 'http://mywebapp.com/sendnames', 
    data: {}, 
    success: function(result) { 
     alert('result: '+result); 
     var obj = jQuery.parseJSON(result); 
     alert('obj: '+obj); 

    // doing rest of stuff 
    } 

}); 

第一次警报来显示正确的结果。结果是:

[ 
    "Richard", 
    "Eric", 
    "John" 
] 

但第二次警报没有来。 我检查了它,它是一个有效的json。为什么我不能用jQuery.parseJSON()解析这个json。提前致谢。

+0

'alert('obj:'+ obj);'show'Richard,Eric,John'? – Musa

+0

你是什么意思,“不能”? – Linuxios

+2

这可能是因为jQuery已经检查过类型,而你的结果已经是JSON对象了。尝试提醒typeof结果并看看你得到了什么。或访问预期的属性之一。 – Alex

回答

2

尝试添加返回类型:数据类型:JSON

$.ajax({ 
     type: 'POST', 
     url: 'http://mywebapp.com/sendnames', 
     data: {}, 
     dataType:'json', 
     success: function(result) { 
      console.log('result: '+result);   
     // doing rest of stuff 
     } 

    }); 

“JSON”:
评估响应为JSON并返回一个JavaScript对象。在jQuery 1.4中,JSON数据以严格的方式被解析;任何格式不正确的JSON都会被拒绝并引发解析错误。 (有关正确的JSON格式的更多信息,请参阅json.org。) “jsonp”:使用JSONP加载JSON块。添加额外的“?callback =?”到您的URL的末尾来指定回调。除非缓存选项设置为true,否则通过向URL追加查询字符串参数“_ = [TIMESTAMP]”来禁用缓存。 http://api.jquery.com/jQuery.ajax/

+2

jQuery.parseJSON仍然是错误的,因为dataType:json会导致jQuery在内部执行该操作。结果变量将已经包含一个JS对象。 –

1

通过$.getJSON更换$.ajax。这保证在内部触发$.parseJSON,所以result已经是所需的JS对象。

$.getJSON({ 
    type: 'POST', 
    url: 'http://mywebapp.com/sendnames', 
    data: {}, 
    success: function(obj) { 
     alert('obj: '+obj); 
     // doing rest of stuff 
    } 
}); 
0

尝试用添加dataType:'text',它将返回字符串作为结果。并且您的代码将按照您的预期运行。

0

See the accepted answer here

You're parsing an object. You parse strings, not objects; jQuery.parseJSON only takes strings.

因为$.ajax已经被解析的数据,result是JavaScript对象不是一个字符串。 parseJSON需要一个字符串参数。

FROM DOCS(更上.ajax() data types here):

The json type parses the fetched data file as a JavaScript object and returns the constructed object as the result data. To do so, it uses jQuery.parseJSON() when the browser supports it; otherwise it uses a Function constructor

+0

在你的答案http://stackoverflow.com/questions/8631977/parsejson-returns-null-on-valid-object json对象被声明和初始化客户端在这里情况是不一样的即在这里结果对象是来自可以是“任何”的外部ajax调用! –

+0

我猜''mywebapp.com/sendnames'返回的MIME类型为JSON,因此jQuery.parseJSON()由jquery自动运行数据。 – robasta