0

I am a newbie attempting to use XMLHttpRequest. I have studied numerous examples scattered across the Internet. I have no problems using the GET method, but when I tried switching to POST it fails to transfer the parameters. :(

Here is my stripped down example which replicates the problem:

Javascript:

function GetPostTest(url)
{
  var req       = null;
  var postParms = 'p1=x&p2=y';
  var getParms  = '';
  getParms = 'g1=a&g2=b';
  if ( getParms )  url += '?'+getParms;
  req = new XMLHttpRequest
  if ( req )
  {
    req.open( 'POST', url, true );
    req.setRequestHeader( "Content-type", "application/x-www-form-urlencoded" );
    req.setRequestHeader( "Content-length", postParms.length );
    req.setRequestHeader( "Connection", "close" );
    req.onreadystatechange = function()
    {
      if ( req.readyState == 4 && req.status == 200 )
      {
        alert( 'Got Stuff Back: ' + req.responseText );
      }
    }
    req.send( postParms );
  }
}

Server:

<?php
foreach ( $_POST as $key=>$value )      echo htmlspecialchars(' _POST['.$key.']=['.$value.']');
foreach ( $_GET as $key=>$value )       echo htmlspecialchars(' _GET['.$key.']=['.$value.']');
foreach ( $_REQUEST as $key=>$value )   echo htmlspecialchars(' _REQUEST['.$key.']=['.$value.']');
exit;
?>

In this example, the server just reports back all of the GET and POST parameters it received which are then shown in the alert box. I have thrown a couple of GET parameters in there also. The parameters I pass are:

  • GET: g1=a&g2=b
  • PUT: p1=x&p2=y

The alert box shows: "Got Stuff Back: _GET[g1]=[a] _GET[g2]=[b] _REQUEST[g1]=[a] _REQUEST[g2]=[b]". This tells me that it is sending to the server okay, and coming back okay, just that the POST variables are not coming through.

I turn off the getParms so I only send POST parameters and then I see no variables. I turn off any combination of the three setRequestHeader()'s or other variations I see in sample code, and it does not change anything.

I am testing with Google Chromium Version 24.0.1312.56 Ubuntu 11.10 (24.0.1312.56-0ubuntu0.11.10.1) and Apache on Xubuntu 2.2.20-1ubuntu1.3 with PHP.

Thanks for your analysis. What does it take to fix this to push the POST parameters through?

4

1 回答 1

0

我刚刚复制了你的代码并尝试了它,它工作得很好。

于 2013-03-07T01:24:12.500 回答