[英]Ajax POST-request doesn't come through to PHP
我正在使用Ajax向我的php文件发出HTTP POST请求,但是我没有得到所需的结果。 $ _POST和$ _GET都是空的。 我想我忽略了什么,但我不知道是什么。
这是我发出请求的代码:
this.save = function() {
alert(ko.toJSON([this.name, this.description, this.pages]));
$.ajax("x", {
data: ko.toJSON([this.name, this.description, this.pages]),
type: "post", contentType: "application/json",
success: function(result) { alert(result) },
error : function(jqXHR, textStatus, errorThrown) { alert(textStatus + errorThrown)}
});
};
请注意,我在第3行警告JSON.JSON是正确的,因此第5行的输入有效。
我在PHP中的测试方法:
header('Content-type: application/json; charset=utf-8');
echo json_encode(array_merge($_POST, $_GET));
exit;
我得到的响应是一个空数组。
json_encode(array('success' => true));
我在页面中找到了 - 所以URL是正确的。 您正在发送JSON请求,这就是$ _POST和$ _GET都为空的原因。 尝试发送如下数据:
$.ajax("x", {
data: { data: [this.name, this.description, this.pages] },
type: "post",
success: function(result) { alert(result) },
error : function(jqXHR, textStatus, errorThrown) { alert(textStatus + errorThrown)}
});
现在查看$_POST["data"]
。
或者如果您需要使用JSON请求,则需要在PHP文件中反序列化它:
$.ajax("x", {
data: { data: ko.toJSON([this.name, this.description, this.pages]) },
type: "post",
success: function(result) { alert(result) },
error : function(jqXHR, textStatus, errorThrown) { alert(textStatus + errorThrown)}
});
然后解码:
$json = $_POST['json'];
$data = json_decode($json);
如果要在POST正文中发送纯JSON请求:
$.ajax("x", {
data: ko.toJSON([this.name, this.description, this.pages]),
type: "post",
contentType: 'application/json',
success: function(result) { alert(result) },
error : function(jqXHR, textStatus, errorThrown) { alert(textStatus + errorThrown)}
});
接着:
$data = json_decode(file_get_contents("php://input"));
请注意, php://input
是一个只读流,允许您从请求正文中读取原始数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.