gpt4 book ai didi

javascript - Ajax - 返回的 json 对象在 ie 中为空

转载 作者:行者123 更新时间:2023-11-30 05:38:00 25 4
gpt4 key购买 nike

您好,我有一个通过 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.

链接:http://msdn.microsoft.com/query/dev12.query?appId=Dev12IDEF1&l=EN-GB&k=k(VS.WebClient.Help.SCRIPT5007)

最佳答案

我无法使用您的示例代码重现该问题。我已经在 Safari 和 IE 11 上测试了您的代码。

这是我使用的示例代码(根据您的修改):

PHP 代码示例

<?php
$output = array();
$output[0] = 'Name';
$output[1] = 'Description for Item: ' . $_POST['id'];
$output[2] = 'Price';
echo json_encode($output);
exit();
?>

因为我不知道 $itemname、$itemdescription 或 $itemprice 是什么,所以我硬编码了值,除了传入的 id。

HTML 代码示例

<html>
<head>
<title></title>
</head>
<body>
<div id="name"></div>
<div id="desc"></div>
<div id="price"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
var $Xhr = $.ajax({
type: "POST",
url: "./add.php",
data: {
id: 1
},
dataType: "json",
success: function () {},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
$Xhr.done(function renderData(data){
document.getElementById("name").innerHTML = data[0];
document.getElementById("desc").innerHTML = data[1];
document.getElementById("price").innerHTML = data[2];
});
</script>
</body>
</html>

注意事项:
- 由于示例“add.php”文件的位置,我在 Ajax URL 中使用“./”。
- 我使用一个对象作为数据而不是字符串。这就是我通常构建数据变量的方式。
- 除了成功之外,我尝试使用 $.done 并且仍然能够检索数据。

输出:

Name
Description for Item: 1
Price

尝试使用 $.done 方法,看看是否对您有帮助。 https://api.jquery.com/deferred.done/

我还建议在开发人员工具中监控网络以验证请求和响应。

关于javascript - Ajax - 返回的 json 对象在 ie 中为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22428195/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com