[英]PHP is not able to read data sent in jQuery.ajax POST
JavaScript code: JavaScript代码:
var data = {"hiSO": "my very complex - nested objects/arrays - data object"};
var j = jQuery.noConflict();
j.ajax({
type: "POST",
url: "postTestingResult.php",
contentType: "application/json; charset=utf-8",
data: {"data": JSON.stringify(data)},
dataType: "json",
success: ajaxSuccess,
error: ajaxError
});
PHP Code: PHP代码:
header('Content-Type: application/json');
if(!empty($_POST['data'])) {
$data = json_decode($_POST['data']);
//do things with data
echo json_encode(array("success" => "thanks for the info!"));
} else {
echo json_encode(array("error" => "'data' is not set or is NULL"));
}
No matter how I structure the data, $_POST['data'] always seems to be empty (specifically, Undefined). 无论我如何构造数据,$ _ POST ['data']始终似乎为空(特别是未定义)。 If you want a full copy of the data object I am using, check out this JSFiddle . 如果您想要我正在使用的数据对象的完整副本,请查看此JSFiddle 。 Appreciate the help, thank you! 感谢您的帮助,谢谢!
You've told the server you're sending JSON (via contentType: "application/json; charset=utf-8"
), but you're not sending JSON, you're sending URI-encoded data. 您已经告诉服务器您正在发送JSON(通过contentType: "application/json; charset=utf-8"
),但是您没有发送JSON,而是发送URI编码的数据。 This is because you've given jQuery an object for the data
option (an object with one property, whose value is a JSON string). 这是因为您为jQuery提供了data
选项的对象(具有一个属性,其值为JSON字符串的对象)。
Your PHP code expects URI-encoded data, so to fix it just remove the contentType
option so jQuery uses its default. 您的PHP代码需要URI编码的数据,因此要解决此问题,只需删除contentType
选项,以便jQuery使用其默认值。
If you really want to send JSON instead (which would require changing your PHP), change 如果您确实要发送JSON(这需要更改PHP),请更改
data: {"data": JSON.stringify(data)},
to 至
data: JSON.stringify(data),
or 要么
data: JSON.stringify({data: data}),
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.