在以前的文章里,我介绍了IE8支持原生的JSON对象,但是,在使用的时候,还需要注意一些问题。很多人使用下面的代码测试,就会报告说JSON未定义:
<html>
<body>
<script type="text/javascript">
alert(typeof JSON);
</script>
</body>
</html>

既然IE8支持了JSON对象,那怎么还不能使用呢?原来,在IE8中使用原生JSON对象是有条件的。微软在介绍JSON对象时也有下面的一段注释:
Starting with JScript 5.8, by default, the JScript scripting engine supports the language feature set as it existed in version 5.7. This is to maintain compatibility with the earlier versions of the engine. To use the complete language feature set of version 5.8, the Windows Script interface host has to invoke IActiveScriptProperty::SetProperty.
Internet Explorer 8 opts into the JScript 5.8 language features when the document mode for Internet Explorer 8 is "Internet Explorer 8 Standards" mode. For other document modes, Internet Explorer uses the version 5.7 feature set.
JScript 5.8 includes native JavaScript Object Notation (JSON) support and the accessor methods for Document Object Model (DOM) prototypes.
由于JSON对象是在JScript 5.8及其以后的版本引入的,所以,默认情况下,IE8使用的是JScript 5.7版本,所以,原生JSON对象是无法使用的。那么,如何使用IE8的原生对象呢?
IE8为了最大限度地保证浏览器的向后兼容性,使原先创建的网页能够正常显示,默认采用的是IE7的渲染引擎,同时,IE8支持多种文档兼容性模式。具体来说有:
  • “模仿 IE8”模式将告诉 Internet Explorer 使用 <!DOCTYPE> 指令来确定如何呈现内容。 标准模式指令将以 Internet Explorer 8 标准模式显示,而 Quirks 模式指令将以 IE5 模式显示。 与 IE8 模式不同,“模仿 IE8”模式遵循 <!DOCTYPE> 指令。
  • “模仿 IE7”模式将告诉 Internet Explorer 使用 <!DOCTYPE> 指令来确定如何呈现内容。 标准模式指令以 Internet Explorer 7 标准模式显示,而 Quirks 模式指令以 IE5 模式显示。 与 IE7 模式不同,“模仿 IE7 模式”遵循 <!DOCTYPE> 指令。 对于很多网站来说,这是首选的兼容性模式。
  • IE5 模式呈现内容的方式如同使用了 Internet Explorer 7 的 Quirks 模式来显示内容,这与 Internet Explorer 5 显示内容的方式非常相似。
  • IE7 模式:无论页面是否包含 <!DOCTYPE> 指令,IE7 模式呈现内容的方式均如同使用了 Internet Explorer 7 的标准模式来显示内容。
  • IE8 模式可最大程度地支持行业标准(包括 W3C 级联样式表级别 2.1 规范 和 W3C 选择器 API),并提供对 W3C 级联样式表级别 3 规范(工作草案) 的有限支持。
  • Edge 模式将告诉 Internet Explorer 以可用的最高级别模式显示内容。 对于 Internet Explorer 8,这等同于 IE8 模式。 假设 Internet Explorer 的将来版本支持更高级别的兼容性模式,那么,设置为 Edge 模式的页面将以该版本支持的最高级别的模式显示。 当使用 Internet Explorer 8 查看时,这些相同的页面仍会以 IE8 模式显示。
详细介绍可以参见MSDN文档:定义文档兼容性(http://msdn.microsoft.com/zh-cn/library/cc288325(VS.85).aspx)。
注意:X-UA-compatible 标头不区分大小写;不过,它必须显示在网页中除 title 元素和其他 meta 元素以外的所有其他元素之前的标头中。
所以,要使用IE8的原生JSON对象,可以采取下面几种方法:
方法1:定义<!DOCTYPE> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>孟宪会:JSON测试</title>
</head>
<body>
<script type="text/javascript">
alert(typeof JSON);
</script>
</body>
</html>

方法2:设置X-UA-compatible 标头

<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" >
<title>孟宪会:JSON测试</title>
</head>
<body>
<script type="text/javascript">
alert(typeof JSON);
</script>
</body>
</html>
或者
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=8" >
<title>孟宪会:JSON测试</title>
</head>
<body>
<script type="text/javascript">
alert(typeof JSON);
</script>
</body>
</html>

在实际编程程序的时候,最好的办法是进行判断,如果不支持原生的JSON,那么就是要json2.js提供的对象即可。