今天做php的一個項目,打算用jquery ajax向后台發送post類型請求,發送的數據類型是json。但是頻頻出錯,不是報500錯誤,就是在后取的值為空的。幾經周折才把問題解決。
總結了兩種ajax發送post請求的寫法:
前端關鍵代碼1:
//變量data是我的js對象經過JSON.stringify(data)處理之后的json字符串
$.ajax({
contentType: 'application/json; charset=utf-8', //這行可有可無都行
type: 'POST',
url: "addinvest", //thinkphp的控制器方法
data: data,
success: function (message) {
console.log(message);
},
error: function (message) {
console.log(message);
}
});
后端關鍵代碼1:
public function addinvest(){
$inputjson = file_get_contents('php://input');
$obj = json_decode($inputjson);
if(is_object($obj)){
echo ($obj->invest_name);
}
}
前端代碼2:
$.ajax({
// contentType: 'application/json; charset=utf-8',
contentType:'application/x-www-form-urlencoded', //這行可有可無都行
type: 'POST',
url: "addinvest",
data:{
data:data,
// "data":data //也可以
},
success: function (message) {
console.log(message);
},
error: function (message) {
console.log(message);
}
});
后端代碼2:
public function addinvest(){
$jsonstr = $_POST["data"];
$obj = json_decode($jsonstr);
echo ($obj->invest_name);
}
需要注意:
echo可以返回數值和字符串,但還不可以返回對象;非數組類型的json數據在后台不能轉換成數組.但是可以轉換成對象。