2014-07-10 30 views
0

我有以下代碼和輸出,並且我不能很好地解碼json數據上的任何錯誤。誰能幫我找到這個錯誤Jquery - Ajax:SyntaxError:JSON.parse:意外字符

CODE:

 $.ajax({ 
      'type': 'get', 
      'data': {}, 
      'dataType': 'json', 
      'url': 'dashboard/data/'+type, 
      'complete': function(data) { 
       var top10Value = JSON.parse(data); 
       $.each(top10Value, function(key,value){ 
        console.log(key+" -- "+value); 
       }); 

      } 
     }); 

OUTPUT:

[{"name":"Bubble Witch Saga 2","impressions":10749},{"name":"Grinder","impressions":11284},{"name":"Loovoo","impressions":12336},{"name":"Injustice God Among Us","impressions":12786},{"name":"Bookmyshow","impressions":13182},{"name":"Angry Bird","impressions":15404},{"name":"Flipkart","impressions":16856},{"name":"CNN-IBN","impressions":17230},{"name":"Fore Square","impressions":17595},{"name":"NDTV","impressions":19542},{"name":"Whatsapp","impressions":19976}] 
+4

你不需要使用'JSON.parse' - 你有'dataType'設置爲'json' - 根據JSLint你的迴應是有效的 – tymeJV

+0

你也想使用'success'選項而不是'complete '接收響應'數據'。這兩個事件沒有通過相同的參數。 –

回答

1

如果指定數據類型:JSON,結果在jQuery是已經被解析。

此外,完整的 函數參數正在返回表示結果的對象而不是結果本身。

這種情況下你應該使用var top10Value = JSON.parse(data.responseText);

0

jQuery是足夠聰明解析響應,因爲它是,即使未指定dataType被。

在你的情況,它被指定,因此,它是已解析data是解析的JSON對象。

你在做什麼,因此解析Object

醫生說:

dataType: (default: Intelligent Guess (xml, json, script, or html))

Type: String

The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:

+0

我讀過兩次JQuery自動分析JSON,但對我來說並非如此。那個怎麼樣? – user1835565

1

數據已經回到只JSON格式,

$.ajax({ 
     'type': 'get', 
     'data': {}, 
     'dataType': 'json',//Return Json Format 
     'url': 'dashboard/data/', 
     'complete': function(data) { 
      //data returned already json format only 
      //var top10Value = JSON.parse(data); 
      $.each(top10Value, function(key,value){ 
       console.log(key+" -- "+value); 
      }); 

     } 
    });