javascript - 在 php 中获取 POSTed JSON 数组
问题描述
如何发送POST
请求以及JSON
数组main.php
以返回 的值key_1
?我下面的当前方法不起作用,我不知道如何解决这个问题。
script.js:
var array = {};
array["key_1"] = "obj_1";
array["key_2"] = "obj_2";
array["key_3"] = "obj_3";
var http = new XMLHttpRequest();
http.open("POST", "main.php");
http.onload = function () {
document.querySelector("p").innerHTML = this.responseText;
}
http.send(array);
main.php:
<?php
$params = json_decode(file_get_contents("php://input"));
echo ($params["key_1"]);
?>
index.html:
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<p></p>
</body>
</html>
解决方案
file_get_contents()
不解析内容。您需要通过json_decode()
.
<?php
$params = json_decode(file_get_contents("php://input"), true);
echo ($params["key_1"]);
?>
推荐阅读
- java - 无法在 windows7 上运行 vlc
- jmeter - 使用带有 jmeter 的wiremock 使用占位符(或生成唯一ID)
- .net - WinForms Control.PointToScreen 和高分辨率屏幕
- ios - 有没有办法通过不添加按钮的任何色调颜色来将“withRenderingMode(.alwaysTemplate)”与默认图像一起使用?
- android - React Native 第二个 ScrollView 不起作用
- android - RecyclerView 对动态添加的 ImageView 进行洗牌
- excel - 有没有办法将测试用例 Excel 表导入 VSTS?
- nginx - nginx 和主机重定向/mysql
- python - 如何将 pygalmesh 网格对象写入二进制 STL 文件?
- javascript - 无法使用代理捕获 customElements 上的访问器调用?