jQuery $.post 发送的变量是正确的,但 PHP 什么也没收到


jQuery $.post sends vars correct, but PHP receives nothing

我有一个jQuery脚本,它将用户名密码发送到PHP文件,该文件检查该用户是否存在并返回JSON用户对象。在非 IE 浏览器中工作正常,但 IE 失败。

奇怪的是,IE"firebug"说一切都很好,但PHP脚本没有收到任何变量......

这是请求正文:

用户名=Johanderowan&password=1234

这些是请求标头(出于安全原因,我省略了一些变量(:

请求 = POST/1.0/account/login.json HTTP/1.1
接受 = /
原产地 = [DEVURL]
接受语言 = nl-NL
UA-CPU = AMD64
接受编码 = gzip, deflate
User-Agent = Mozilla/5.0(兼容;微星 9.0;视窗NT 6.1;赢64;x64;三叉戟/5.0(
Host = [DEVURL]
内容长度 = 66
连接保持活动状态 缓存控制无缓存

响应正文为(前三个空数组分别为 $_GET、$_POST 和 $_REQUEST(:

数组 ( (
数组 ( (
数组 ( (
{"状态":"错误","消息":"未指定用户名或密码.","httpCode":500}

这是请求脚本:

$('.mobyNowLoginForm form').bind('submit', function(){  
    var username = $(this).find('.username').val();  
    var password = $(this).find('.password').val();  
    $.post('[url]/1.0/account/login.json', {
        username: username,
        password: password
    }, function(response) {
        // do something
    }, "JSON");  
    return false;
});

我完全不知道这里可能出了什么问题...

IE 似乎没有在跨域请求中发送正确的连接类型。内容类型始终设置为"文本/纯文本"。

在此博客文章中阅读有关此缺点的更多信息:http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx

我们通过解析 php://input 字符串并将其设置为 $_POST vars 在服务器上修复了此问题。

if ($_SERVER['REQUEST_METHOD'] == 'POST' && count($_POST) == 0) {
    $postData = file_get_contents('php://input');
    $postVars = explode('&', $postData);
    foreach ($postVars as $postVar) {
        list($key, $var) = explode('=', $postVar);
        $_POST[$key] = $var;
    }
}
您是否

尝试将缓存设置为 false。我遇到了类似的问题,这解决了它:

$.ajax({
  type: 'POST',
  url: '[url]/1.0/account/login.json',
  dataType: 'json',
  data: {
      username: username,
      password: password
  },
  cache: false,
  success: function() {
      // Do something
  }
});

希望对您有所帮助!

斯蒂芬

编辑

问题也可能出在您的请求 URL 中。您尝试调用 .json 文件。 您可以尝试改为调用.php文件。

确保将其放在.php文件中:

header("Content-Type: application/json");