我有以下的Ajax請求:切換到POST
// JavaScript
function myFunc(pid) {
$.ajax({
type : "GET",
url : "testback.php",
contentType : "application/json; charset=utf-8",
dataType : "json",
data : {
q : "testrequest",
pid : pid
},
success : function(data) {
console.log(data)
},
error : function(jqXHR, status, error) {
console.log(status, error);
}
});
}
// PHP
require_once ("dbconnect.php");
if (isset ($_GET ['q'])) {
if ($_GET ['q'] == "testrequest") {
$pid = $_GET ['pid'];
$query = "SELECT * FROM `tab1` WHERE `pid` = " . $pid;
$json = array();
if ($result = $link->query ($query)) {
while ($row = $result->fetch_assoc()) {
array_push ($json, $row);
}
}
header ("Content-type: application/json; charset=utf-8");
die (json_encode ($json));
exit();
}
die();
}
它發送一個請求,我的MySQL數據庫,並返回預期的輸出。
但是,我現在想切換到POST
,而不是GET
。
當我剛換用POST GET:
// JavaScript
function myFunc(pid) {
$.ajax({
type : "POST", // POST
url : "testback.php",
contentType : "application/json; charset=utf-8",
dataType : "json",
data : {
q : "testrequest",
pid : pid
},
success : function(data) {
console.log(data)
},
error : function(jqXHR, status, error) {
console.log(status, error);
}
});
}
// PHP
require_once ("dbconnect.php");
if (isset ($_POST ['q'])) { // POST
if ($_POST ['q'] == "testrequest") { // POST
$pid = $_POST ['pid']; // POST
$query = "SELECT * FROM `tab1` WHERE `pid` = " . $pid;
$json = array();
if ($result = $link->query ($query)) {
while ($row = $result->fetch_assoc()) {
array_push ($json, $row);
}
}
header ("Content-type: application/json; charset=utf-8");
die (json_encode ($json));
exit();
}
die();
}
我得到以下錯誤在控制檯:
parsererror SyntaxError: Unexpected end of JSON input
請求負載仍然q=testrequest&pid=1
。
我還需要改變什麼,才能從GET
切換到POST
?
使用'json_decode()'在$ _ POST查詢 – ixe
@ ixe:你能告訴我,究竟在哪裏? – user1170330
@ user1170330刪除'contentType'和'dataType'設置 – postrel