javascript - 从 javascript 发送 HTTP 请求时,如何从 PHP 脚本返回数组?
问题描述
嗨,我是 PHP 新手,我遇到了一个问题,我想向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>
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数组。
一些文档和相关阅读:
推荐阅读
- json - 在 wso2 esb 中连接两个 JSON 响应
- python - 上传“osmapi.OsmApi.ApiError:请求失败:404 - 未找到 - b”时出错
- abap - OPEN-SQL 查询在abap 4 EXEC SQL 中不起作用
- machine-learning - 训练损失和验证损失总是变为 0.00000e+00
- java - 是否可以使用 WildFly 在 Java 应用程序中运行 gRPC 服务器?
- r - 总结 R 中两列的数据框
- python-3.x - Docker:构建后文件丢失
- java - 无法使用 Springboot 对静态文件进行版本控制(缓存破坏)
- c# - 为什么 SetBasePath 在 .NET Core 3.1 中不起作用?我试过添加 nuget 包,但它不起作用
- arrays - 是否可以通过引用第 n+1 个元素找到数组末尾的地址?