【问题标题】:Undefined type Error When passing array from php to Javascript using json.encode [duplicate]使用json.encode将数组从php传递到Javascript时出现未定义类型错误[重复]
【发布时间】: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.

我不知道出了什么问题。我错过了什么吗? 以下是我在试图找出我的错误时注意到的一些事情,这可能会有所帮助:

  1. typeof 返回“对象”
  2. 我尝试这样做只是为了看看会发生什么: 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 =&gt; response.json()).then(result =&gt; doThingsWithYourData(result)).catch(e =&gt; console.error(e))。另外,不要使用innerHTML,如果需要文本,请使用.textContent,如果需要 DOM 节点,请使用 DOM 函数(createElement、append 等)。

标签: javascript php html arrays


【解决方案1】:

问题是您使用了非同步请求。

document.getelement..... 部分不等待请求的答复。所以你必须把它放在请求的回调函数中

【讨论】:

  • 谢谢你说得通。我想我可以将我所有的数组处理函数放入 php 中,然后只将我需要的元素提供给 js,这可能会使事情变得更容易。谢谢
猜你喜欢
  • 2011-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-28
  • 2013-05-15
  • 1970-01-01
相关资源
最近更新 更多