[英]JSON object received as NULL during ajax POST method to server
到處搜尋,似乎找不到答案。 我正在使用ajax發布填充了對象的字符串化數組,JSONLint可以直接發送到php腳本,該腳本現在僅返回它。
但是,在傳輸過程中,對象變為NULL。 我發送JSON字符串的方式有問題嗎? 我真的很感謝一些建議,可以給出虛擬的擊掌感。 謝謝你的時間!
JS
var newDist = $("#distanceEl").val();
var newDate = $("#dateEl").val();
var newId = this.arr.length + 1;
var newStat = new Stat(newId, newDist, newDate);
this.arr.push(newStat);
var newData = JSON.stringify(this.arr);
console.log(newData);
$.ajax({
url : "php/post.php",
type: "POST",
dataType : "json",
contentType : "application/json",
data: newData,
success: function(response)
{
console.log("Ajax: " + JSON.parse(response));
},
error: function(requestObject, error, errorThrown)
{
console.log("Error with Ajax Post Request:" + error);
console.log(errorThrown);
}
});
的PHP
$jsonData = json_decode($_POST['newData']);
echo json_encode($jsonData);
由於您在請求中使用contentType : "application/json"
,因此發送的數據不會填充$_POST
。 您可以使用file_get_contents('php://input')
您也不需要JSON.parse
響應,因為您已經在使用dataType : "json"
在你的js上
$.ajax({
url : "php/post.php",
type: "POST",
dataType : "json",
contentType : "application/json",
data: newData,
success: function(response)
{
console.log("Ajax: " , response);
},
error: function(requestObject, error, errorThrown)
{
console.log("Error with Ajax Post Request:" + error);
console.log(errorThrown);
}
});
在您的PHP上:
$input = file_get_contents('php://input');
$jsonData = json_decode($input);
echo json_encode($jsonData);
另一個選擇是,不要將您的數據作為contentType : "application/json"
發送contentType : "application/json"
在您的js上:
var newData = [{"id":1,"distance":"1.2mi","date":"1/2/18"},{"id":1,"distance":"2.3mi","date":"1/4/18"},{"id":3,"distance":"1.7mi","date":"1/6/18"},{"id":4,"distance":"defaultDis","date":"defaultDate"}];
$.ajax({
url : "data.php",
type: "POST",
dataType : "json",
data: {newData : newData}, //Pass your data as object. No need to stringtify newData
success: function(response)
{
console.log("Ajax: " , response);
},
error: function(requestObject, error, errorThrown)
{
console.log("Error with Ajax Post Request:" + error);
console.log(errorThrown);
}
});
在您的PHP上:
echo json_encode($_POST['newData']);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.