好的,这是我的ajax请求:
$("#scoreForm").submit(function(e){
e.preventDefault();
var nickName = $('#nickName').val();
var gameScore = parseInt($('#gameScore').text());
var result = { 'result' : '{ "nick":"'+nickName+'", "score":'+gameScore+' }' };
//var result = { "nick":nickName, "score":gameScore };
$.ajax({
url: "http://localhost:8888/snake/addScore.php",
type: "POST",
data: result,
//dataType: "jsonp",
success: function(data){
alert("siker");
},
error: function(jqXHR, textStatus, errorThrown) {
alert("bukta " + textStatus);
//console.log(data);
}
});
return false;
});
和我的php进程代码:
$json_decoded = json_decode($_POST['result'],true);
//$nick = $_GET['nick'];
//$score = $_GET['score'];
$mysqli = new mysqli("localhost", "root", "root", "snake",8889);
//$mysqli->query("INSERT INTO scores(nickName,score) VALUES('".$nick."', ".$score.")");
$mysqli->query("INSERT INTO scores(nickName,score) VALUES('".$json_decoded['nick']."', ".$json_decoded['score'].")");
echo "true";
现在我将数据插入到数据库中,但是ajax仍然会触发错误事件。我读到,如果我将dataType设置为jsonp它会变低,但后来我得到解析错误,我怎么过去呢?
答案 0 :(得分:4)
如果您在php脚本中访问$ _POST变量,则需要按照JSON对象的方式引用它们:
$_POST['nick']
$_POST['score']
如果你想把这些项目称为$ _POST ['result']并使用你的json解码方法,你需要这样打包:
var result = { result : { "nick":nickName, "score":gameScore } };