2010-09-27 83 views
1

我發現這一點:獲取沒有JSON.parse的json對象?

使用Python輸出:

print ‘Content-type: text/x-json\n\n’ 
print json.dumps([{'title':arr['title']}]) 

,並得到JSON字符串使用jQuery:

$ajax( 
    success: function(msg){ 
     if(msg[0].title) alert(msg[0].title); 
    } 
) 

它的工作原理,誰可以告訴我,爲什麼它是什麼?謝謝〜

回答

3

的jQuery內部調用上有它的現代瀏覽器JSON.parse如果Content-Type是JSON

 return window.JSON && window.JSON.parse ? 
      window.JSON.parse(data) : 
      (new Function("return " + data))(); 
+0

感謝您的回答〜medr – Zhaiduo 2010-09-27 02:29:06

1

我相信jQuery是能夠確定基於您發送的報頭中的響應類型和自動將其評估爲JSON。

1

如果設置dataType"json"或者你設置和content-type頭包含字符串"json",它試圖解析它,you can see the logic at work here

if (typeof data === "string") { 
    // Get the JavaScript object, if JSON is used. 
    if (type === "json" || !type && ct.indexOf("json") >= 0) { 
    data = jQuery.parseJSON(data); 

    // If the type is "script", eval it in global context 
    } else if (type === "script" || !type && ct.indexOf("javascript") >= 0) { 
    jQuery.globalEval(data); 
    } 
} 

如果你很好奇, jQuery.parseJSON()的來源是here

+0

感謝您的鏈接〜nick – Zhaiduo 2010-09-27 02:29:25