【发布时间】: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]
}
我环顾四周,发现了一些其他问题,建议检查页面中是否包含<!DOCTYPE html>(确实如此),但这似乎没有任何效果。我还读到这应该从 IE8 开始工作,所以不确定发生了什么。
- 有谁知道为什么对象在 IE 中显示为空值?
- 最好的跨浏览器解决方案是什么?
谢谢, 加文
【问题讨论】:
-
试试
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