简体   繁体   中英

How can I make right XHR POST request in Firefox 28.0?

My server php script POST array is empty after I make a simple XHR POST in Firefox 28.0. The request is same origin.

In my js script that triggers request I have:

$(function(){
$("#head").click(function(){
var invocation=new XMLHttpRequest();
var url="test.php";
var body="hello";
if (invocation)
{
    invocation.open("POST",url, true);
    invocation.onreadystatechange=handler;
    invocation.send(body);
}
function handler(evtXHR){
    if(invocation.readyState===4)
    {
    if(invocation.status===200)

    {

       alert("success");
    }

    }
}
});
});

And in my php file I have:

<?php
header('Access-Control-Allow-Origin: *');
$data=$_POST['body'];
var_dump($data);
?>

Below is the interaction between client and server:

Request Method:     POST
Status Code:    HTTP/1.1 200 OK

Request header:

User-Agent: Mozilla/5.0 (X11; Linux i686; rv:28.0) Gecko/20100101 Firefox/28.0
Referer:    .......
Pragma: no-cache
Host:   ..........
Content-Type:   text/plain; charset=UTF-8
Content-Length: 5
Connection: keep-alive
Cache-Control:  no-cache
Accept-Language:    en-US,en;q=0.5
Accept-Encoding:    gzip, deflate
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

Request Body: Hello

Response Header

X-Powered-By:   PHP/5.2.17
Transfer-Encoding:  chunked
Server: Apache
Keep-Alive: timeout=5, max=100
Date:   Wed, 16 Apr 2014 19:04:55 GMT
Content-Type:   text/html
Connection: Keep-Alive
access-control-allow-origin:    *

Please,help figure out what's happening. Why POST array is empty after successful request? Thanks.

You're encoding your request body as plain text. PHP doesn't parse that into $_POST .

Either access the raw message body…

file_get_contents('php://input')

or encode the data in the request in a format that PHP can understand.

var data="hello";
var body = "someKeyName=" + encodeURIComponent(data);

// ...
invocation.open("POST",url, true);
invocation.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
invocation.send(body);

and

$data=$_POST['someKeyName'];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM