簡體   English   中英

JSON.stringify 在 IE10 中不起作用

[英]JSON.stringify not working in IE10

我正在嘗試解析一些表單數據以生成 JSON 數據以在 ajax 請求中發送。 以下 HTML 是我代碼的過度簡化版本。 我正在使用 APS.Net MVC4 並且我呈現的視圖生成以下 HTML:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <link href="/Content/site.css" rel="stylesheet"/>
    <script src="/Scripts/modernizr-2.6.2.js"></script>
</head>
<body>

<div class="test-class" data-my-attribute="1"></div>
<div class="test-class" data-my-attribute="2"></div>
<div class="test-class" data-my-attribute="3"></div>

<script src="/Scripts/jquery-1.8.2.js"></script>

<script type="text/javascript">
    $(function () {
        jsonObj = [];
        $(".test-class").each(function () {
            var myAttribute = $(this).data('my-attribute');
            item = {}
            item["MyAttribute"] = myAttribute;
            jsonObj.push(item);
        });
        var data = { SomeOtherData: 1234, MyAttribs: jsonObj };
        console.log(JSON.stringify(data));
    });
</script>
</body>
</html>

在 Chrome 中,控制台中的輸出按預期輸出......

{
    "SomeOtherData": 1234,
    "MyAttribs": [{
        "MyAttribute": 1
    }, {
        "MyAttribute": 2
    }, {
        "MyAttribute": 3
    }]
}

...但在 IE 中,對象顯示為 null ...

{
    "SomeOtherData": 1234,
    "MyAttribs": [null, null, null]
}

我環顧四周,發現了一些其他問題,建議檢查頁面中是否包含<!DOCTYPE html> (確實如此)並且這似乎沒有任何影響。 我也讀過這應該從 IE8 開始工作,所以不確定發生了什么。

  1. 有誰知道為什么對象在 IE 中顯示為空值?
  2. 什么是最好的跨瀏覽器解決方案?

謝謝,加文

我看到的唯一奇怪的是:

  item = {}

應該:

  var item = {}; // 'var' and semicolon

有時IE相當嚴格。

在我的情況下使用@palvo 說console.dir(obj)

另一種選擇是來自douglascrockford 的 JSON2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM