我正在使用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));
取代我的PHP示例中的第二行,那么URL就是正确的。答案 0 :(得分:2)
您正在发送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
是一个只读流,允许您从请求正文中读取原始数据。