[英]How to return an array from PHP script when an HTTP request is sent from javascript?
您好我是新来的PHP和我卡上的问题,我想送一个HTTP请求到PHP
脚本,它应该返回一个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>
get_info.php:
<?php
$return_array = [[1, "h"],[2, "he"],[3, "hel"],[4, "hell"],[5, "hello"]];
return $return_array;
?>
json_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
然后在JavaScript
var myArray = JSON.parse(xhr.responseText);
console.log(myArray);
重新制作一个js数组。
一些文档和相关读物:
使用echo
而不是return
...这不是一个被调用的函数; 这是一个代码片段,仅将动态数据替换为静态文本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.