我需要编写一个脚本来接收和解析 POST 数组中的 JSON 数组。为了做到这一点,我首先尝试将任何旧的 JSON 数据发送到我的脚本,以便我可以使用一些东西。
我的接收脚本是用 PHP 编写的(但也可以用 Javascript 完成。)现在,我只是序列化 POST 数组并将其写入文本文件以确保有内容进入。它正在写的是一个空数组,尽管。
我正在尝试使用 ajax 请求发送数据。这就是我现在所拥有的:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
$(document).ready(function() {
var jsondata = JSON.stringify({
val1:"this",
val2:"that"
});
$.ajax({
url: "http://api.mydomain.com/test/index.php",
method: "POST",
data: {json: jsondata},
contentType: "application/json",
success: function(data){alert(JSON.stringify(data));},
error: function(errMsg) {
alert(JSON.stringify(errMsg));
}
});
});
</script>
</head>
<body>
</body>
</html>
我也尝试了很多变体,包括
- 不对 jsondata 进行字符串化
- 将数据更改为:
data: jsondata
- 在请求中使用
type:
而不是method:
- 在请求中包括
datatype: "json"
以及其他一些我什至不记得的变体。我错过了一些简单的东西吗?或者有更简单的方法来完成这个吗?
编辑:添加我的 index.php 文件
if (isset($_POST)){
// This line is commented out because it breaks it.
//$jspost = json_decode($_POST['json']);
$jsser = serialize($_POST);
echo "I'm here.";
// Write to text file
$myfile = "response.txt";
$fh = fopen($myfile, 'w') or die("can't open file");
$now = date("n/j/y g:i:s a");
fwrite($fh, $now."\r\n");
fwrite($fh, "I received a POST.\r\n");
fwrite($fh, $jsser);
fwrite($fh, "\r\n\n");
fclose($fh);
}
原文由 user3353762 发布,翻译遵循 CC BY-SA 4.0 许可协议
JS
发送一个 JSON 字符串
服务.php
解码并处理接收到的对象
反之亦然,如果你想从 php 发送一个 JSON 并将其解码为 JS
PHP
JS