【问题标题】:jQuery AJAX post is empty when content-type is set to JSON UTF-8当内容类型设置为 JSON UTF-8 时,jQuery AJAX 帖子为空
【发布时间】: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 有效。

标签: php jquery json


【解决方案1】:

您应该再次阅读jquery documentation,尤其是涵盖datadataType 参数的部分。 data 必须是键/值对象,即:

data: { 'userid': userid }

...对于 dataType,允许的值为 xml、html、text、json 和 jsonp。如果您的 PHP 脚本发送了合适的 Content-type 标头(例如 header('Content-type: text/json');,那么您可以简单地将此参数保留为默认值(“智能猜测”)。jQuery 将根据其内容类型标头推断响应类型。您应该发送无论如何,标头,否则服务器可能会假定您正在发送 HTML 并自己添加 HTML 内容类型标头,然后 jQuery 会阻塞。 在 PHP 脚本中设置 internal encodingoutput encoding 可能也是一个好主意,以便它正确理解请求并发送格式正确的 UTF-8 响应。

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

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

【讨论】:

    【解决方案2】:

    我在同一个问题上斗争的时间比我想承认的要长,然后我从 PHP 文档中读到了这个:

    $_POST:传递给当前变量的关联数组 脚本通过 HTTP POST 方法 when 使用 application/x-www-form-urlencodedmultipart/form-data 作为 HTTP 请求中的 Content-Type

    虽然我试图在没有 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 次。

    【讨论】:

      【解决方案3】:

      您应该尝试使用$.post 并在必要时将其与事件绑定。 我是为 mousemove 事件做的:

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

      【讨论】:

        猜你喜欢
        • 2013-12-26
        • 2023-03-30
        • 2017-01-22
        • 2020-03-20
        • 2023-04-11
        • 2013-05-09
        • 2011-08-12
        • 1970-01-01
        • 2018-07-24
        相关资源
        最近更新 更多