最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - $_POST array empty in PHP after an a request with post data - Stack Overflow

programmeradmin3浏览0评论

I am sending parameters using this method to my server php but I get the values that you post shipping:

function post(path, parameters) {
var http = new XMLHttpRequest();
console.log(parameters);
http.open("POST", path, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send(parameters);
}

php :

public function tracking_referidos(){
    $this->autoRender = false;
    $result = array();
    $result['post'] = $_POST;
    echo json_encode($result);
    exit;
}

result : {"post":{"referrer":"","event":"eventrid","hash":"45hfkabdus"}}

I am sending parameters using this method to my server php but I get the values that you post shipping:

function post(path, parameters) {
var http = new XMLHttpRequest();
console.log(parameters);
http.open("POST", path, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send(parameters);
}

php :

public function tracking_referidos(){
    $this->autoRender = false;
    $result = array();
    $result['post'] = $_POST;
    echo json_encode($result);
    exit;
}

result : {"post":{"referrer":"","event":"eventrid","hash":"45hfkabdus"}}

Share Improve this question edited Nov 27, 2015 at 16:22 NHTorres asked Nov 27, 2015 at 15:58 NHTorresNHTorres 1,5382 gold badges21 silver badges39 bronze badges 2
  • look at this one stackoverflow./questions/8207488/… – nahab Commented Nov 27, 2015 at 16:01
  • 1 JSON data doesn't map to $_POST automatically, for that you need to send the data as application/x-www-form-urlencoded (key=value&key2=value2 and so on). Alternatively, you can get the raw POST data, which is a JSON string like so: file_get_contents('php://input'); – Elias Van Ootegem Commented Nov 27, 2015 at 16:08
Add a ment  | 

1 Answer 1

Reset to default 10

You're sending a JSON string. PHP doesn't decode that data and map it to the $_POST super global automatically. If you want PHP to do that, you need to send the data as application/x-www-form-urlencoded (ie similar to the URI of a get request: key=value&key2=value2).

You can send data using the application/json content type, but to get at the request data, you need to read the raw post body. You can find that in the php://input stream. Just use file_get_contents to read it:

$rawPostBody = file_get_contents('php://input');
$postData = json_decode($rawPostBody, true);//$postData is now an array
发布评论

评论列表(0)

  1. 暂无评论