[英]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.