JSON object undefined in Internet Explorer 8

2019-01-04 21:47发布

Currently I'm writing a JavaScript file and have the following line:

var res = "JSON=" + JSON.stringify(result);

result is being set just above this line. The issue I'm having is that IE8 (IE8 only, that is) is reporting to me that JSON is undefined somehow. I'm not sure what to make of this since, as I understood it, IE8 is a browser that implemented JSON support. Does anyone have any idea what might be going on?

8条回答
何必那么认真
2楼-- · 2019-01-04 22:19

Other things that absence of doctype or wrong doctype, or some error with html syntax, will force IE to use document modes different from what you expect.

I was using simple "" in a test document and the absence of TITLE tag as a child of HEAD tag made window.JSON become undefined.

Remember always that it's better to test the resource against the version of browser. And, if your users can use IE's with emulation of document modes, it's better you have a piece of code to provide the JSON.parse and JSON.stringify when natives are undefined.

查看更多
Luminary・发光体
3楼-- · 2019-01-04 22:20

In my case the undefined error was because I was missing a JSON library.

You can add JSON object like this (replace the relative path with your own path):

<script>
        if (typeof window.JSON == 'undefined') {
          document.write('<script src="../scripts/json2.js"><\/script>'); 
        }
</script>

For json2 library: http://cdnjs.com/libraries/json2/

There is also a json3 library: http://cdnjs.com/libraries/json3/

Then you can refer to it in your code:

var array = [];
array[1] = "apple";
array[2] = "orange";
alert(JSON.stringify(array));
查看更多
倾城 Initia
4楼-- · 2019-01-04 22:28

Check jQuery version. jQuery 2.0 drops support for IE 6, 7 and 8. Use jQuery 1.x instead, which is still officially supported. you can use this Code.

<script src="http://code.jquery.com/jquery-1.9.0.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.js"></script>

read more about jquery migrate.

if not working check this article.

查看更多
萌系小妹纸
5楼-- · 2019-01-04 22:31

Make sure you're actually in IE 8 mode by using the preferred method, a standards doctype...

<!DOCTYPE html>

...or the undesired method, the X-UA-Compatible meta tag/header...

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

See Defining Document Compatibility for more information.

查看更多
forever°为你锁心
6楼-- · 2019-01-04 22:32
function parseJson(jsonString) {
    if ($.browser.msie && $.browser.version < 8) {
        return eval('(' + jsonString + ')');
    }
    else {
        return JSON.parse(jsonString);
    }
}
查看更多
看我几分像从前
7楼-- · 2019-01-04 22:40

May happen despite <!DOCTYPE html> if the page encoding is UTF-8 with BOM (byte order mark). Try saving the file as UTF-8 without BOM, using a suitable text editor.

查看更多
登录 后发表回答