当内容类型设置为 JSON UTF-8 时,jQuery AJAX 帖子为空
我正在尝试使用 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, '[email protected]');
$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 响应。我做错了什么?
I'm trying to post some very simple data to a php file using jquery and then get the json response but I seem to be running into a road block somewhere. Here is my 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>
and here is the php page it posts to
<?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, '[email protected]');
$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);
}
?>
The problem im having is that if I use contentType: "application/json; charset=utf-8" the $_POST is always empty. And when I remove contentType: "application/json; charset=utf-8" the $_POST is populated but I cant get a json response. What am I doing wrong??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该再次通读 jquery 文档,尤其是涵盖
数据的部分
和dataType
参数。data
必须是键/值对象,即:...对于 dataType,允许的值为 xml、html、text、json 和 jsonp。如果您的 PHP 脚本发送合适的
Content-type
标头(例如header('Content-type: text/json');
,那么您只需将此参数保留在默认(“智能猜测”)。jQuery 将从其内容类型标头推断响应类型,否则,服务器可能会假设您正在发送 HTML 并添加 HTML 内容类型标头本身。然后就窒息了。设置 内部编码 和 < a href="http://www.php.net/manual/en/function.mb-http-output.php" rel="nofollow">输出编码 在 PHP 脚本中,以便它理解正确请求并发送格式正确的 UTF-8 响应。
为了进一步调试,您可能需要:
$_POST
数组以及发送到服务器上文本文件的响应You should read through the jquery documentation once more, especially the part that covers the
data
anddataType
parameters.data
must be a key/value object, i.e.:...and for dataType, allowed values are xml, html, text, json, and jsonp. If your PHP script sends a suitable
Content-type
header (e.g.header('Content-type: text/json');
, then you can simply leave this parameter at the default ('Intelligent guess'). jQuery will infer the response type from its content type header. You should send the header anyway because otherwise, the server will probably assume you're sending HTML and add a HTML content type header itself, which jQuery then chokes on.It's probably also a good idea to set the internal encoding and output encoding in your PHP script, so that it understands the request correctly and sends a well-formed UTF-8 response.
For further debugging, you might want to:
$_POST
array and the response you're sending to a text file on the server我与同样的问题斗争的时间比我愿意承认的要长,然后我从 PHP 文档中读到了这一点:
我试图在没有 jquery 的情况下做到这一点,但我构建了自己的 xmlhttprequest 对象。真正让我意识到当查询采用 JSON 格式或除 %encoded 类型以外的任何格式时 $_POST 不会被填充的事情是,当我最终放弃并尝试使用 JQuery 时,我查看了他们发送的原始帖子数据,毕竟不是 JSON,他们只是使用了“application/x-www-form-urlencoded”,并在发送之前将我的 JSON 转换为 urlencoded 格式。然后 PHP 愉快地用我的数据填充 $_POST 数组,因为它是“百分比编码”的,根本不是 JSON 数据。我认为 $_POST 是一些神奇的东西,可以读取大多数内容类型并神奇地填充,我认为这是原始数据,直到我想起 $HTTP_RAW_POST_DATA,但它已经贬值了,人们现在使用“php://input”并读取通过这样做:
所以人们应该能够在那里找到它们的 JSON,但它还不会自动解析为单独的变量。
我希望我至少能帮助别人,这篇文章已经有 4 年了,但它说它已经被浏览了 7,000 多次。
I was fighting with the same problem for longer than I would like to admit, and then I read this from the PHP documentation:
I was trying to do it without jquery though, I built my own xmlhttprequest object. The thing that really made me realise that $_POST doesn't get populated when the query is in JSON format, or in any format other than the %encoded type, was that when I finally gave up and tried to use JQuery, I looked at the raw post data they were sending, and it wasn't JSON after all, they had just used "application/x-www-form-urlencoded" and had converted my JSON to urlencoded format before sending it over. PHP then happily populated the $_POST array with my data because it was "percent-encoded" and not JSON data at all. I thought $_POST was some magical thing that would read most content-types and magically populate, I thought it was the raw data, until I remembered $HTTP_RAW_POST_DATA, but that was depreciate and people now use "php://input" and read it by doing something like this:
So one should be able to find their JSON in there, but it won't automagically be parsed into separate variables yet.
I hope I helped someone else at least, this post is 4 years old, but it says it's been viewed more than 7,000 times.
您应该尝试使用
$.post
并在必要时将其与事件绑定。我为鼠标移动事件做到了这一点:
You should try using
$.post
and bind it with an event if necessary.I did it for a mousemove event: