21,893
社区成员




$str = {"id":5, "cat":4, "price":3, "num": 2};
$.ajax({
type: 'POST',
url: 'update_product.php',
data: $str,
dataType:'json',
contentType:"application/json;charset=utf-8",
success: function(data) {
$("#result").html(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
$("#result").html("failed content: " + $str['id']+" " + $str['cat'] + " " + $str['price'] + " " + $str['num'] + "<br>failed reason: " + textStatus+" " + errorThrown + "<br>" + XMLHttpRequest.responseText);
alert(XMLHttpRequest.responseText);
}
});
<?php
header('Content-type: application/json');
echo $_POST["id"]; //不行
echo json_decode($_POST['data']);//不行
echo file_get_contents("php://input"); //这样可以得到a=1&b=2&c=3类似get的数据,但我不想这样处理
?>
header('Content-type: application/json');
$data = json_decode(file_get_contents("php://input"), true);
$id = $data["id"];
$cat = $data["cat"];
$price = $data["price"];
$num = $data["num"];
echo $id." ".$cat." ".$price." ".$num;
前台这样
$("#submitBtn").click(function(){
//$str = {"id":5, "cat":4, "price":3, "num": 2};
$str = '{"id":"5", "cat":"4", "price":"3", "num":"2"}';
$.ajax({
type: 'POST',
url: 'update.php',
data: $str,
dataType:'json',
contentType:"application/json;charset=utf-8",
success: function(data) {
$("#result").html(JSON.parse(data));
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
$("#result").html("failed content: " + $str['id']+" " + $str['cat'] + " " + $str['price'] + " " + $str['num'] + "<br>failed reason: " + textStatus+" " + errorThrown + "<br/>" + XMLHttpRequest.responseText);
//alert("error " + XMLHttpRequest.responseText);
alert(JSON.parse(data));
}
});
});
输出:
failed content: undefined undefined undefined undefined
failed reason: parsererror SyntaxError: Unexpected number
5 4 3 2
为什么还会报错呢?版主帮看看?这两天才弄php,小白之处见谅,谢谢。