【发布时间】:2011-02-16 20:09:38
【问题描述】:
我正在尝试使用 jquery 将一些非常简单的数据发布到 php 文件中,然后获取 json 响应,但我似乎在某处遇到了障碍。这是我的jQuery:
<script>
$(function() {
$('.resend-verify').click( function() {
var userid = $(this).attr('rel');
$.ajax({
type: "POST",
url: "resend_verification.php",
contentType: "application/json; charset=utf-8",
data: "userid=" + userid,
dataType: "json",
success: function(data) {
console.log(data.response);
if(data.response == 'error') {
$('div.alert').addClass('error');
}
$('div.alert').html(data.comment);
}
});
});
});
</script>
这是它发布到的 php 页面
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST") { // Check For Post
require '../../config.php'; // Site Settings
require '../../connectors/mysqlConnector.php';
include $DIR['php'] . 'functions.php'; // Common Functions
//var_dump(json_decode($_POST));
$UserID = $_POST['userid'];
$userSQL = "SELECT p.user_firstname,p.user_lastname,a.user_email,a.user_salt FROM web_profiles p INNER JOIN web_accounts a ON p.user_id = a.user_id WHERE p.user_id ='" . $UserID . "'";
$userQuery = mysql_query($userSQL);
//var_dump($userSQL);
$user = mysql_fetch_object($userQuery);
if (!$user->user_email) {
$response = array('response' => 'error', 'comment' => 'User not found');
} else {
// Send User Verification Email
$sendmail = new sendMail();
$message = createUserAuthEmail($user->user_firstname, $user->user_lastname, $user->user_salt, $Site['register_email_body']);
$content['body'] = '<br /><br />' . $message . '<br /><br />DO NOT REPLY TO THIS EMAIL! IT IS ONLY AN AUTOMATED NOTIFICATION EMAIL!';
$sendmail->set(to, $user->user_email);
$sendmail->set(subject, 'Action Required to Activate Membership');
$sendmail->set(from, 'no-reply@domain.com');
$sendmail->set(html, true);
$sendmail->getParams($content);
$sendmail->parseBody();
$sendmail->setHeaders();
if ($sendmail->send()) {
$response = array('response' => 'success', 'comment' => 'email sent');
} else {
$response = array('response' => 'error', 'comment' => 'Error sending email');
}
}
echo json_encode($response);
}
?>
我遇到的问题是,如果我使用 contentType: "application/json; charset=utf-8" $_POST 总是空的。当我删除 contentType: "application/json; charset=utf-8" 时, $_POST 已填充,但我无法获得 json 响应。我做错了什么??
【问题讨论】:
-
请尝试使用描述问题的标题;它将帮助有类似问题的人找到您的问题,并使其他人更容易回答您的问题。这次我为你编辑了问题:)
-
...并阅读标记语法帮助。
-
尝试在 php 中回显之前设置
header('Content-type: application/json'); -
加上默认的 contentType
application/x-www-form-urlencoded通常效果最好 -
跳过 contentType 属性。 @MrHyde 建议的默认
application/x-www-form-urlencoded有效。