当从javascript发送HTTP请求时,如何从PHP脚本返回数组?
嗨,我是PHP新手,我遇到了一个问题, 我想向当从javascript发送HTTP请求时,如何从PHP脚本返回数组?,javascript,php,Javascript,Php,嗨,我是PHP新手,我遇到了一个问题, 我想向PHP脚本发送一个HTTP请求,它应该返回一个2x2数组。但用我的密码我什么也没收到 index.html: <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <script> var xhr =
PHP
脚本发送一个HTTP请求,它应该返回一个2x2数组。但用我的密码我什么也没收到
index.html:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
var xhr = new XMLHttpRequest();
xhr.open("GET", "get_info.php");
xhr.onload = function () {
console.log(xhr.responseText);
};
xhr.send();
</script>
</body>
</html>
json\u encode()
该数组,以及echo
(不返回!)生成的json字符串:
<?php
$return_array = [[1, "h"],[2, "he"],[3, "hel"],[4, "hell"],[5, "hello"]];
echo json_encode($return_array);
// remove the trailing ?> just to make sure you don't send an unwanted newline, space or smth
再次使用它制作js数组
一些文件和相关内容如下:
echo
而不是return
。。。这不是一个被调用的函数;它是一个代码片段,只是将动态数据替换为静态文本
<?php
$return_array = [[1, "h"],[2, "he"],[3, "hel"],[4, "hell"],[5, "hello"]];
echo json_encode($return_array);
// remove the trailing ?> just to make sure you don't send an unwanted newline, space or smth
var myArray = JSON.parse(xhr.responseText);
console.log(myArray);