2012-08-31 53 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