2011-11-16 70 views
3
工作

我已經使用了以下方法:JSON.stringify不IE

JSON.stringify(json,null,2); 

這產生在所有瀏覽器選項卡式輸出除外IE:在IE中,它顯示單行。是null的問題,如果是的話有什麼選擇?

+1

什麼版本的IE瀏覽器您使用的是什麼樣的?從IE8向上支持'stringify':http://blogs.msdn.com/b/ie/archive/2008/09/10/native-json-in-ie8。aspx – Lycha

+0

我的觀衆使用的更重要。我已經在IE7中測試過它。 –

回答

2

看看the MSDN documentation,它看起來像Internet Explorer期望一個函數或對象的第二個參數,否則它會引發異常。

您可以嘗試使用undefined而不是null。例如:

JSON.stringify(json,undefined,2) 
+0

謝謝我嘗試過。我想我可能只需要按照\ t,\ n,\ r逐行旋轉 - 非常可怕! –

+0

你不必添加第三個參數,只是未定義就足夠了:) ..感謝這個偉大的提示! –

3

好。這可能不是解決你的問題正是,但可能幫助別人來這裏:

是的,作爲Lycha提到的,這是支持IE8及以上。

因此,如果您仍然收到「JSON未定義」錯誤,則它必須是「DOCTYPE」問題。

因此,請提及適當的DOCTYPE(並且最好將您的文檔保存爲有效的xhtml格式(即,標籤等)..),並且應該正常工作。

沒有提及(正確)DOCTYPE通常在IE中創建了很多與CSS相關的問題,在這種情況下也是JSON。

-

(IE === '壞')

+0

謝謝,添加正確的DOCTYPE爲我做了訣竅。剛剛救了我一個小時的谷歌搜索...;)+1 – Aletheios

4

可以使用jquery.min.js或最新的1.8.2或版本,並把這個在<head>元素:

<meta http-equiv="X-UA-Compatible" content="IE=8" /> 

它適用於IE8及以上版本。

3

一個正確的doctype IE8的支持,它是:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
1
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
2

有可能是它可能無法包含的文檔類型或元標記或沒有可能在我的情況下工作,因爲這樣的情況我不得不按照解釋的方式弄清楚這一點。

要將json對象發回服務器,必須支持json.strinfy。要在IE上支持相同,請從https://github.com/douglascrockford/JSON-js下載json2.js並在您的視圖中提及。下面的代碼片斷爲我工作,我希望它幫助別人。

//include jquery library from your preferred cdn or local drive. 
<!-- include json2.js only when you need JSON.stringfy method --> 
<script type="text/javascript" src="~/scripts/json2.js"></script> 
<script type="text/javascript"> 
function button_click() { 
//object to post back to the server. 
var postData = { "Id": $('#hfUserId').val(), "Name": $('#Name').text(), 
"address": new Array() }; 
var address = new Array(); var addr; 
addr = { "HouseNo": "1", "Street": "ABC", "City": "Chicago", "State": "IL" }; 
address[0] = addr; 
addr = { "HouseNo": "2", "Street": "DEF", "City": "Hoffman Est", "State": "IL" }; 
address[1] = addr; 
//make ajax call to server to save the data 
$.ajax({ 
    url: '@Url.Action("myAction", "MyController")', 
    type: 'POST', 
    dataType: 'json', 
    contentType: 'application/json; charset=utf-8', 
    data: JSON.stringify(postData), 
    async: true, 
    success: function (data) { alert('User Saved'); }, 
    error: function (data) { alert('Could not save User'); } 
    }); 
} 
</script> 

地址列表的模型如下。請注意,屬性名稱與addr對象相同,並且具有get和set。

public class Address 
{ 
    public string HouseNo { get; set; } 
    public string Street { get; set; } 
    public string City { get; set; } 
    public string State { get; set; } 
} 

控制器動作將是什麼下面

[HttpPost] 
public ActionResult myAction(string Id, string Name, List<Address> address) 
{ 
    JsonResult result = null; 
    result = new JsonResult 
       { 
        Data = new 
        { 
         error = false, 
         message = "User Saved !" 
        } 
       }; 
    return result; 
} 
+0

偉大而聰明的答案。你說得對,我們不能添加Doctype或meta標籤。 – Sunny