【问题标题】:JSON.stringify not working in IE10JSON.stringify 在 IE10 中不起作用
【发布时间】:2013-12-02 19:08:55
【问题描述】:

我正在尝试解析一些表单数据以生成 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]
}

我环顾四周,发现了一些其他问题,建议检查页面中是否包含&lt;!DOCTYPE html&gt;(确实如此),但这似乎没有任何效果。我还读到这应该从 IE8 开始工作,所以不确定发生了什么。

  1. 有谁知道为什么对象在 IE 中显示为空值?
  2. 最好的跨浏览器解决方案是什么?

谢谢, 加文

【问题讨论】:

  • 试试console.dir(jsonObj)。它输出什么?
  • 嗨@Teemu,我在console.log 语句之前放置了一个调试器,并验证了jsonObj 看起来一切正常。处理数据属性的是 jQuery,并且工作正常。
  • 你可以试试json3这样的回填库之一。这应该会产生一致的结果。
  • @Pavlo,运行 console.dir(jsonObj) 并得到:function item() { [native code] } , function item() { [native code] } , function item() { [native code] } { 0 : function item() { [native code] } , 1 : function item() { [native code] } , 2 : function item() { [native code] } }
  • 虽然这不是解决方案,但请使用var item = {}而不是item = {}

标签: javascript jquery json internet-explorer cross-browser


【解决方案1】:

我看到的唯一奇怪的是:

  item = {}

应该是:

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

有时候IE很严格..

【讨论】:

  • 看起来 IE 有一个名为 item 的原生函数。
  • 你可能把我从几个小时的挫折中拯救了出来!谢谢:)
【解决方案2】:

在我的情况下用作@palvo sayed console.dir(obj)

其他选择是来自douglascrockford的JSON2

【讨论】:

猜你喜欢
  • 2013-11-13
  • 2013-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-02
  • 2013-08-03
  • 2017-05-11
  • 2013-09-16
相关资源
最近更新 更多