我正在尝试使用ajax从javascript中将一些数据保存到数据库中。 这是我的代码部分,我创建请求并将json格式的数据发送到save / save1.php:
urlPath = "save/save1.php";
var request = new XMLHttpRequest();
request.addEventListener('load',function() {
console.log(this.responseText);
});
idGame = "1";
data = JSON.stringify({'idUser': idUser, 'idGame': idGame, 'score': score});
request.addEventListener('error', function () {
document.write('There was an error with AJAX request!');
});
request.addEventListener('load', this.onSuccess);
request.onreadystatechange = function(){
if(request.readyState == 4){
alert(request.responseText);
}
};
request.open("POST", urlPath);
request.setRequestHeader('Content-Type','application/json');
request.send(data);
这是我的save1.php文件:
<?php
include '../database_connection.php';
var_dump($_POST);die(); //this was just for debuging and it prints that array is empty
if (isset($_POST['idUser']) && isset($_POST['idGame']) && isset($_POST['score']))
{
$rez = $_POST['score'];
$idGame = $_POST['idGame'];
$idUser = $_POST['idUser'];
$query = 'INSERT INTO scores (idUser, idGame, score) VALUES ('.$idUser.','.$idGame.','.$rez.');';
$sucess = mysql_query($query);
if($sucess)
{
echo 'yes';
}
else
{
sendJsonResponse(array(
'error' => "not saved"));
}
}
else
{
sendJsonResponse(array(
'error' => "not set"));
};
function sendJsonResponse($data) {
header('Content-Type: application/json');
die(json_encode($data));
}
我做错了什么? :(
编辑: 我解决了我找到了解释:
我刚刚注意到你也在设置contentType ...为了工作,你将无法使用$ _POST var。相反,您需要从file_get_contents(“php:// input”)中获取“应该”为您提供原始JSON字符串的数据。从那里你应该能够使用PHP的json_decode将它变成一个真正的PHP对象。
所以我添加到我的save1.php文档中:
$data = json_decode(file_get_contents('php://input'), true);
if (isset($data['idUser']) && isset($data['idGame']) && isset($data['score']))
{
$rez = $data['score'];
//and so on...