当内容类型设置为 JSON UTF-8 时,jQuery AJAX 帖子为空

发布于 2024-10-17 21:12:33 字数 2944 浏览 3 评论 0原文

我正在尝试使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

走过海棠暮 2024-10-24 21:12:33

您应该再次通读 jquery 文档,尤其是涵盖 数据的部分dataType 参数。 data 必须是键/值对象,即:

data: { 'userid': userid }

...对于 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 响应。

为了进一步调试,您可能需要:

  • 在 PHP 中添加一些日志记录代码,例如,转储 $_POST 数组以及发送到服务器上文本文件的响应
  • 发布测试请求使用像curl或wget这样的东西到你的PHP脚本,看看响应是否是你所期望的,
  • 让你的javascript发布到一个虚拟脚本,除了记录请求并发送一个空响应之外什么也不做; 查看是否可以
  • 使用脚本调试器(例如 Firefox 上的 Firebug,或者 Chrom[e|ium] 中内置的东西) 单步调试您的 javascript;在成功处理程序中设置一个断点,看看是否命中,如果命中,响应包含什么内容

You should read through the jquery documentation once more, especially the part that covers the data and dataType parameters. data must be a key/value object, i.e.:

data: { 'userid': userid }

...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:

  • add some logging code to your PHP, for example, dump the $_POST array and the response you're sending to a text file on the server
  • post a test request to your PHP script using something like curl or wget, and see if the response is what you expect
  • have your javascript post to a dummy script that does nothing but log the request and send an empty response; see if that works
  • step through your javascript using a script debugger (e.g. Firebug on Firefox, or the thing that's built into Chrom[e|ium]); set a breakpoint inside the success handler and see if it's hit, and if so, what the response contains
风月客 2024-10-24 21:12:33

我与同样的问题斗争的时间比我愿意承认的要长,然后我从 PHP 文档中读到了这一点:

$_POST:传递给当前变量的关联数组
使用时通过 HTTP POST 方法编写脚本
application/x-www-form-urlencodedmultipart/form-data 作为 HTTP
请求中的内容类型

我试图在没有 jquery 的情况下做到这一点,但我构建了自己的 xmlhttprequest 对象。真正让我意识到当查询采用 JSON 格式或除 %encoded 类型以外的任何格式时 $_POST 不会被填充的事情是,当我最终放弃并尝试使用 JQuery 时,我查看了他们发送的原始帖子数据,毕竟不是 JSON,他们只是使用了“application/x-www-form-urlencoded”,并在发送之前将我的 JSON 转换为 urlencoded 格式。然后 PHP 愉快地用我的数据填充 $_POST 数组,因为它是“百分比编码”的,根本不是 JSON 数据。我认为 $_POST 是一些神奇的东西,可以读取大多数内容类型并神奇地填充,我认为这是原始数据,直到我想起 $HTTP_RAW_POST_DATA,但它已经贬值了,人们现在使用“php://input”并读取通过这样做:

$rawPOST = file_get_contents('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:

$_POST: An associative array of variables passed to the current
script via the HTTP POST method when using
application/x-www-form-urlencoded or multipart/form-data as the HTTP
Content-Type
in the request.

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:

$rawPOST = file_get_contents('php://input');

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.

童话 2024-10-24 21:12:33

您应该尝试使用 $.post 并在必要时将其与事件绑定。
我为鼠标移动事件做到了这一点:

$.fn.saveArray = function() { 
    var data = {data: selectednumbers};
    $.post('clickmap.php',{
        data:JSON.stringify(data)
        //contentType: 'application/json',
    });
};

You should try using $.post and bind it with an event if necessary.
I did it for a mousemove event:

$.fn.saveArray = function() { 
    var data = {data: selectednumbers};
    $.post('clickmap.php',{
        data:JSON.stringify(data)
        //contentType: 'application/json',
    });
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文