$_POST var 不填充,而是$HTTP_RAW_POST_DATA 获取数据


$_POST var not populated instead $HTTP_RAW_POST_DATA takes data

我在javascript中使用这个函数与服务器PHP脚本进行通信:

    ajax = function( url, ready, json=null, method = 'post') {
    var response, request = xhr();
    request.open( method, url, true );
    request.onreadystatechange = function() {
        if( request.readyState == 4 ) {
            if( typeof ready == 'function' ){
                return ready( request );
            } else {    return JSON.parse( request.responseText );}
        } 
    }
    if(json !== null){
        request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
        return request.send( JSON.stringify( json ) );
    }else { return request.send( null );}
}

我在使用 post method 打开连接后进行了XMLHttpRequest。我还设置了setRequestHeader来解析JSON: ("Content-Type", "application/json;charset=UTF-8");,我用这个函数从html form中收集data

formToValues = function (id) {
    var i, values = {}, form = document.getElementById(id);
    //var fields = form.querySelectorAll('input,textarea,select'),
    for (i = 0; i < form.length ;i++) {
        if( form.elements[i].name !== "" ){
            values[form.elements[i].name] = form.elements[i].value;
        }
    }
    return values;
}

ajax('a.php', function(response){
    console.log(response);
}, formToValues("regForm") );

这也是我html form

<form id="regForm" action="javascript:;" method="post" />
<p>
<label for="name">Name</label>
<input type="text" name="name" value="xhr" />
<label for="email">Email:</label>
<input type="email" name="email" value="ro@ew.gq" />
<label for="password">Password:</label>
<input type="password" name="password" value="pass" />
<input type="button" value="Search" />
</p>

现在我在脚本中接收数据时遇到php Liitle 问题: a.php

<?php
var_dump(  $GLOBALS );
$ar= array( "a"=>2,"b"=>3, "c"=>json_decode( $_REQUEST['params'] ));
echo json_encode($ar);
?>

似乎 PHP 将我从 Javascrip 发送的数据作为字符串并将其存储在HTTP_RAW_POST_DATA

["HTTP_RAW_POST_DATA"]=> string(51) "{"name":"xhr","email":"ro@ew.gq","password":"pass"}"

    "array(7) {
  ["GLOBALS"]=>
  array(7) {
    ["GLOBALS"]=>
    *RECURSION*
    ["HTTP_RAW_POST_DATA"]=>
    string(51) "{"name":"xhr","email":"ro@ew.gq","password":"pass"}"
    ["_POST"]=>
    array(0) {
    }
    ["_GET"]=>
    array(0) {
    }
    ["_COOKIE"]=>
    array(0) {
    }
    ["_FILES"]=>
    array(0) {
    }
    ["_REQUEST"]=>
    array(0) {
    }
  }

现在我可以用php://input获取数据不会成为问题,但我担心安全性,它确实很好,还有一件事需要考虑:从 PHP 版本 5.6.0 开始。 $HTTP_RAW_POST_DATA — 原始 POST 数据已弃用~ 那我该怎么办?特坎克斯

当请求内容类型为application/json时,PHP 不会填充 $_POST 超全局(仅 application/x-www-form-urlencodedmultipart/form-data (。

建议使用 json_decode()php://input .