我一整天都在苦苦挣扎,我似乎无法正确使用 $.ajax 函数将 JSON 对象发送到 PHP 文件。我最终正确地发送了它,但现在它拒绝解码。
//JQuery 文件
var user =
{
"email" : document.getElementById('email1').value,
"password" : document.getElementById('pwd1').value,
"fname" : document.getElementById('firstname').value,
"lname" : document.getElementById('lastname').value,
"gender" : Validator.getGender(),
"dob" : document.getElementById('dob').value
};
JSON.stringify(user);
user = {json:user};
$.ajax({
type: "POST",
url: "register.php",
dataType: 'json',
data: user,
success: function(result)
{
alert("It worked :D");
alert(result);
},
failure: function()
{
alert('whoops');
}
});
//PHP文件
<?php
$json = $_REQUEST['json'];
$json = stripslashes($json);
$jsonobj = json_decode($json);
$fname = $jsonobj->fname;
$lname = $jsonobj->lname;
$password = $jsonobj->password;
$email = $jsonobj->email;
$gender = $jsonobj->gender;
$dob = $jsonobj->dob;
echo $gender;
?>
我在做一些完全愚蠢的事情吗?我现在只是呼应了性别变量,但实际上我打算使用它来将其输入数据库。
提前致谢 :)
编辑:
如果我的 php 文件如下所示,它将如何工作:
session_start();
$db = mysql_connect("localhost", "root");
if(!$db)
{
die("DB connection failed: " . mysql_error());
}
$db_select = mysql_select_db("tinyspace", $db);
if(!$db_select)
{
die("DB connection failed: " . mysql_error());
}
$json_string = $_REQUEST["json"];
$jsonobj = json_decode($_REQUEST["json"]);
$fname = $jsonobj -> fname;
$lname = $jsonobj -> lname;
$pwd = $jsonobj -> password;
$email = $jsonobj -> email;
$gender = $jsonobj -> gender;
$dob = $jsonobj -> dob;
$sql("INSERT INTO tinyspace.users (email, password, firstname, lastname, gender, dob) VALUES ('$email','$password','$fname', '$lname','$gender','$dob')");
if (!mysql_query($sql,$db))
{
die('Error: ' . mysql_error());
}
mysql_close($db);