我正在尝试将JSON对象发送到.php文件。让我烦恼的是,我的 POST 值似乎没有进入 PHP 的 $_POST 数组。这是我的代码:
j查询:
$("#submit").click(function(){
var obj = { //create json object to be sent
"name": $("#name").val(),
"email": $("#email").val(),
"r1": $("#r1").val(),
"r2": $("#r2").val(),
"r3": $("#r3").val(),
"intr1": $("#q1").val(),
"intr2": $("#q2").val(),
"intr3": $("#q3").val(),
"set": "set1"
};
var jsonObj = JSON.stringify(obj);
$.post(
"updateAnswers.php",
jsonObj,
function() {
//location.href = 'set2.php';
}
);
})
.PHP:
if (isset($_POST["jsonObj"])) { // value is empty
$obj = json_decode($_POST['jsonObj'], true);
$name = $obj['name'];
$email = $obj['email'];
$db = mysqli_connect("localhost", "root", "", "concurs");
$sql="INSERT into players values ('$name', '$email', '0', '0', '0')";
mysqli_query($db, $sql);
}
提前感谢!
- 我认为您不需要字符串化
obj
- 尝试将obj
直接传递给$.post
函数。
$.post("updateAnswers.php", obj, function() {
//location.href = 'set2.php';
});
- 在PHP端,值
name
、email
、r1
等将直接在$_POST
数组中,所以你需要访问$_POST['name']
等等。
echo "Name: ". $_POST['name']; //Show name value
var_dump($_POST); //Show all passed values
$sql
字符串不检查 SQL 注入。您必须(至少)将单引号替换为两个单引号,例如:
$sql = "INSERT into players values ('".str_replace("'","''", $name). "', '".str_replace("'","''", $email). "', '0', '0', '0')";
你在obj上使用stringify,然后将其传递给ajax函数。但是 ajax 函数期望对象是 objetct 而不是字符串。因此,只需删除var jsonObj = JSON.stringify(obj);
并使用obj
此外,您必须检查
- 名字
- 电子邮件
- R1
- 。
在你的PHP脚本中而不是jsonObj
因为这是PHP实际上从你的脚本中得到的
这使用 AJAX() 发送:
$.ajax({
type: 'POST',
url: 'updateAnswers.php',
data: {'jsonObj': jsonObj},
success: function(msg) {
alert(msg);
}
});