我正在尝试在localhost上使用YUI3测试一些ajax和JSON解析示例。代码如下:
<!doctype html>
<html>
<head>
<title>YUI 3 Getting started</title>
</head>
<body>
<p id="time">(what time is it?)</p>
<button id="go">What time is it?</button>
<script src="http://yui.yahooapis.com/3.3.0/build/simpleyui/simpleyui-min.js"></script>
<script>
function printTime(id, response) {
try {
var data = Y.JSON.parse(response.responseText);
}
catch (ex) {
data = { time: "ERROR" };
}
Y.one("#time").setContent(data.time);
}
Y.one("#go").on("click", function () {
Y.io("watch.php", {
on: {
success: printTime
}
});
});
</script>
</body>
</html>
这是watch.php:
<?php
header('Content-Type: application/json; charset=utf8');
echo(
json_encode(
array(
"time" => date("g:ia l, M jS")
)
)
);
我已经尝试将文件上传到网络主机,但仍然遇到同样的问题。奇怪的是,它在firefox中运行得非常好,但拒绝在IE9和其他IE模式下运行!IE正在返回此错误代码:c00ce56e
。
有什么想法吗?
IE9对JSON响应非常严格。可以肯定的是,确保为每个JSON响应发送一个带有编码的正确标头。还要确保JSON格式正确。
这是修复:
header('Content-Type: application/json; charset=utf-8');
请注意,字符集必须定义,并且必须是有效的字符集。