【发布时间】:2021-02-10 21:03:32
【问题描述】:
我正在尝试使用 HTTP 请求和 JSON 编码将数组从 PHP 传递到我的 Javascript。但是我不断收到此错误消息:
Uncaught TypeError: Cannot read property '132620' of undefined(我尝试在阵列上呼叫号码 132620。
这是我的 php 代码。
<?php
$myArray = array("num1","num2","num3",....);
$myJSON = json_encode($myArray);
echo $myJSON;
?>
这是我的 javascript 代码的开头:
var getarray;
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 && this.status==200) {
getarray=JSON.parse(this.responseText);
console.log(typeof getarray); //for debugging
}
}
xmlhttp.open("GET","arrayhandling.php",true);
xmlhttp.send();
//and then later I call:
document.getElementById["h2"].innerHTML= getarray[1132620];
//and that's where I get the error.
我不知道出了什么问题。我错过了什么吗? 以下是我在试图找出我的错误时注意到的一些事情,这可能会有所帮助:
- typeof 返回“对象”
- 我尝试这样做只是为了看看会发生什么:
document.getElementById["h2"].innerHTML= getarray;它似乎正在将数组输入到我的 HTML 中。在 HTML 中,标题显示了数组。它显示 num1,num2,num3,... 在被切断之前不带引号或括号
我非常感谢您的帮助,因为我已经被困了很长时间了。谢谢。
顺便说一句,我将本教程用作指南。 https://www.w3schools.com/js/js_json_php.asp
【问题讨论】:
-
在 2021 年的注释中:使用 Fetch API 而不是 XMLHttpRequest。它在获取各种类型的数据方面要好得多,而且在没有过去 XHR 所需的任何荒谬代码的情况下“正常工作”。
fetch("your url").then(response => response.json()).then(result => doThingsWithYourData(result)).catch(e => console.error(e))。另外,不要使用innerHTML,如果需要文本,请使用.textContent,如果需要 DOM 节点,请使用 DOM 函数(createElement、append 等)。
标签: javascript php html arrays