这是我的JS代码:
var person = [];
person[0] = "John";
person[1] = "Doe";
person[2] = 46;
var myData = JSON.stringify(person);
$.ajax({
type: "POST",
url: "test.php",
dataType : "text",
contentType: "application/json; charset=utf-8",
data: myData,
success: function(answer) {
alert(answer);
},
complete: function() {
},
error: function(jqXHR, errorText, errorThrown) {
alert(jqXHR+" - "+errorText+" - "+errorThrown);
}
});
这是php:
if(isset($_POST['myData']))
{
echo "ok";
}
else
{
echo "not_ok";
}
?>
它总是返回“not_ok”。为什么我的PHP代码无法检索JSON?我做错了什么?有人能解释一下吗?
答案 0 :(得分:1)
尝试以下
dataType : "json"
:告诉jQuery你希望它解析返回的JSON
json_encode()
:PHP函数以json格式编码数组。
<强>的JavaScript 强>
var person = [];
person[0] = "John";
person[1] = "Doe";
person[2] = 46;
$.ajax({
type: "POST",
url: "test.php",
dataType : "json", // Set datatype json
data: {myData : person}, // Request Parameters
success: function(answer) {
console.log(answer); // JSON Response
},
complete: function() {
},
error: function(jqXHR, errorText, errorThrown) {
alert(jqXHR+" - "+errorText+" - "+errorThrown);
}
});
<强> PHP 强>
<?php
if(isset($_POST['myData'])){
$status = "ok";
}
else
{
$status = "Not Ok";
}
echo json_encode(array("status" => $status));
exit;
?>
<强>输出强>
Object {status: "ok"}
答案 1 :(得分:0)
您需要一些密钥才能从post / get变量中获取数据
data:{firstname:"John",lastname:"Doe",age:45},
PHP:
$_POST['firstname']
或
data:{data:["John","Doe",45]},
如果你真的想要一个数组
$_POST['data']
答案 2 :(得分:0)
您正在将数组转换为json格式的字符串,而不使用任何名称。但你可以在ajax帖子中发布数组,你不需要对其进行字符串化。 您可以按原样传递数组
data: {myData: person},
var person = [];
person[0] = "John";
person[1] = "Doe";
person[2] = 46;
$.ajax({
type: "POST",
url: "test.php",
dataType : "text",
contentType: "application/json; charset=utf-8",
data: {myData: person},
success: function(answer) {
alert(answer);
},
complete: function() {
},
error: function(jqXHR, errorText, errorThrown) {
alert(jqXHR+" - "+errorText+" - "+errorThrown);
}
});