【发布时间】:2016-04-25 05:37:54
【问题描述】:
我需要编写一个脚本来接收和解析 POST 数组中的 JSON 数组。为了做到这一点,我首先尝试将任何旧的 JSON 数据发送到我的脚本,以便我有一些东西可以使用。
我的接收脚本使用 PHP(但也可以使用 Javascript不过,空数组。
我正在尝试使用 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);
}
【问题讨论】:
-
JSON.stringify(data)在您的成功回调中输出什么? -
我们可以看到你的 index.php 文件的内容吗?一个好的策略是在 php 脚本中执行 vardumps 和 die() 以确保不是服务器端错误。如果没有,console.log(JSON.stringify(data)) 来检查响应。
-
成功回调中 JSON.stringify(data) 的输出是“我在这里。”,这是从 index.php 文件中回显的。
-
我想通了!这是我的 contentType。当我将其设置为“application/x-www-form-urlencoded; charset=UTF-8”而不是“application/json”时,index.php 上的 var_dump 会显示通过的 jsondata 的值。
标签: javascript ajax post