2012-10-02 87 views
3

jQuery的使用jQuery.parseJSON()轉換JSON-字符串對象時使用JSON.parse()一個跨瀏覽器的解決方案:jQuerys缺乏JSON.stringify的

parseJSON: function(data) { 
    if (!data || typeof data !== "string") { 
     return null; 
    } 

    // Make sure leading/trailing whitespace is removed (IE can't handle it) 
    data = jQuery.trim(data); 

    // Attempt to parse using the native JSON parser first 
    if (window.JSON && window.JSON.parse) { 
     return window.JSON.parse(data); 
    } 

    // Make sure the incoming data is actual JSON 
    // Logic borrowed from http://json.org/json2.js 
    if (rvalidchars.test(data.replace(rvalidescape, "@") 
     .replace(rvalidtokens, "]") 
     .replace(rvalidbraces, ""))) { 

     return (new Function("return " + data))(); 

    } 
    jQuery.error("Invalid JSON: " + data); 
} 

但爲什麼沒有使用對象轉換成JSON類似的解決方案JSON.stringify?例如,JSON.stringify在IE7中不起作用,除非包含json2.js。這是jQuerys路線圖上的東西嗎?

回答

3

沒有類似的解決方案,因爲jQuery內部不需要它。目前的立場是如果核心不需要它,並且可以使用普遍接受的方法(包括json2.js或使用所有現代瀏覽器中內置的方法)來實現它。它不需要在覈心。

僅供參考,https://forum.jquery.com/topic/jquery-encodejson

+0

猜生病必須堅持一個條件註釋並將其包含在IE7則。謝謝 – Johan