I am trying to parse some form data to produce JSON data to send in an ajax request. The following HTML is an oversimplified version of my code. I'm using APS.Net MVC4 and my rendered view produces the following 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>
In Chrome the output in the console is output as expected ...
{
"SomeOtherData": 1234,
"MyAttribs": [{
"MyAttribute": 1
}, {
"MyAttribute": 2
}, {
"MyAttribute": 3
}]
}
... but in IE the objects come out as null ...
{
"SomeOtherData": 1234,
"MyAttribs": [null, null, null]
}
I've had a look around and found some other questions that recommend checking that the page has <!DOCTYPE html> in it (which it does) and that doesn't seem to have any effect. I've also read that this should work in from IE8 onward so not sure what's happening.
- Does anyone know why the objects are appearing as nulls in IE?
- What is the best cross-browser solution to this?
Thanks, Gavin
console.dir(jsonObj). What does it output?console.dir(jsonObj)and get: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 = {}instead ofitem = {}