【发布时间】:2014-04-21 02:43:22
【问题描述】:
您好,我有一个通过 ajax 连接到 php 脚本的 javascript 代码。这个 php 脚本返回一个数组。在ajax调用的成功函数中,我使用返回的数组向用户显示信息。这在我尝试过的所有浏览器中都可以正常工作,除了 Internet Explorer。我收到以下错误:
Unable to get property '0' of undefined or null reference
'0' 是数组中第一个元素的索引。代码如下:
JS
$.ajax({
type: "POST",
url: "/add.php",
data: 'id=' + itemid,
dataType: "json",
success: function (data) {
document.getElementById("name").innerHTML = data[0];
document.getElementById("desc").innerHTML = data[1];
document.getElementById("price").innerHTML = data[2];
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
PHP
$output = array();
$output[0] = $itemname;
$output[1] = $itemdescription;
$output[2] = $itemprice;
echo json_encode($output);
exit();
我在成功函数中尝试了console.log(data),在 Internet Explorer 中它返回 null,而在其他浏览器中它返回数组。有谁知道这里出了什么问题?
IE 控制台上的错误代码是 SCRIPT5007。搜索后,这意味着:
You attempted to invoke the Object.prototype.toString or Object.prototype.valueOf method on an object of a type other than Object. The object of this type of invocation must be of type Object.
【问题讨论】:
-
嗯。也许尝试将
data = JSON.parse(data)放在成功函数的开头 - ? -
@rm-vanda dataType 是 json 所以不需要。但是我仍然尝试过,它返回 null
-
开发工具中 IE 中的服务器响应是什么样的?
-
你能试试 alert (typeof data) 和 alert (data.length) 告诉我们你有什么吗?
-
@LShetty typeof 是对象,长度返回以下内容:无法获取未定义或空引用的属性“长度”
标签: javascript php jquery ajax json