我有一个问题,即将带有ajax的json数据发送到php文件,然后使用它上传到服务器。
如果我正在回显变量$email_info->Name
,则返回的数据值为空。
我已经尝试过json_decode,但它不会这样做。
这是我的代码,
Jquery:
$( document ).on('click', '#send_touch', function(){
new_email = [];
new_email.push({
Name: $('#name').val(),
Phone: $('#phone').val(),
Email: $('#email').val(),
Interested_in: $('#interested_in').val(),
User_id: $('#email_user_id').val()
});
new_email = JSON.stringify({Email: new_email}, null, "\t");
$.ajax({
url: "core.php",
type: "post",
data: { NewMail: new_email
},
success: function(data){
alert(data)
},
error: function(){
}
});
});
PHP:
if ($_POST['NewMail']) {
$timeStamp = time();
$new_email = json_decode($_POST['NewMail'], true);
$email_info = $new_email->Email[0];
// New Email
mysql_query("INSERT INTO " . $dbPrefix . "touches (date, user_id, name, phone, email, interested_in, seen, status) VALUES ('".safeSQL($timeStamp)."', '".safeSQL($email_info->User_id)."', '".safeSQL($email_info->Name)."','".safeSQL($email_info->Phone)."', '".safeSQL($email_info->Email)."', '".safeSQL($email_info->Interested_in)."', '0', '1')") or die("Query failed: " . mysql_error());
echo $email_info->Name;
}
如果我在$_POST['NewMail']
的PHP端回复,我会收到这个:
{
\"Email\": [
{
\"Name\": \"John Doe\",
\"Phone\": \"1234567\",
\"Email\": \"john@doe.com\",
\"Interested_in\": \"Text here..\",
\"User_id\": \"1\"
}
]
}
我该如何解决这个问题?
答案 0 :(得分:1)
在PHP中替换此部分:
$new_email = json_decode($_POST['NewMail'], true);
由此:
if (get_magic_quotes_gpc()) {
$_POST['NewMail'] = stripslashes($_POST['NewMail']);
}
$new_email = json_decode($_POST['NewMail'], true);
这应解决问题。
答案 1 :(得分:1)
我在我的服务器上打开了magic_quotes。
我在测试Hossams代码时意识到了这一点:
if (get_magic_quotes_gpc()) {
$_POST['NewMail'] = stripslashes($_POST['NewMail']);
}
所以最后我们可以使用这段代码:
if ($_POST['NewMail']) {
$timeStamp = time();
if (get_magic_quotes_gpc()) {
$_POST['NewMail'] = stripslashes($_POST['NewMail']);
}
$new_email = json_decode($_POST['NewMail'], true);
$email_info = $new_email['Email'][0];
// New Email
mysql_query("INSERT INTO " . $dbPrefix . "touches (date, user_id, name, phone, email, interested_in, seen, status) VALUES ('".safeSQL($timeStamp)."', '".safeSQL($email_info['User_id'])."', '".safeSQL($email_info['Name'])."','".safeSQL($email_info['Phone'])."', '".safeSQL($email_info['Email'])."', '".safeSQL($email_info['Interested_in'])."', '0', '1')") or die("Query failed: " . mysql_error());
var_dump($email_info['Name']);
}
我使用$email_info['Name']
代替$email_info->Name
答案 2 :(得分:0)
您需要指定jquery您的发送数据是JSON类型。请在ajax选项中配置数据类型。例如:
$.ajax({
url: "core.php",
type: "json", //here comes the data's type
data: { NewMail: new_email
},
success: function(data){
alert(data)},
error: function(){
}`