2011-08-15 13 views
6

Estoy tratando de publicar datos en una página PHP y verificar la respuesta. Aquí hay un ejemplo. ¿Qué está mal con este código?POST desde XMLHttp con los parámetros

index.html

<html> 
<head> 
    <title>Post Ajax</title> 
    <script type="text/javascript"> 
     function post(foo, bar) { 
      var xmlhttp = new XMLHttpRequest(); 

      xmlhttp.onreadystatechange = function() { 
       if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { 
        alert(xmlhttp.responseText); 
       } 
      } 

      xmlhttp.open("POST", "ajax.php", true); 
      xmlhttp.send("foo=" + foo + "&bar=" + bar); 
     } 
    </script> 
</head> 
<body> 
    <input type="button" value="Click me" onclick="post('one','two');" /> 
</body> 
</html> 

ajax.php

<?php 
if (array_key_exists('foo', $_POST) && array_key_exists('bar', $_POST)) { 

    $foo = $_POST['foo']; 
    $bar = ($_POST['bar']); 
    // do stuff with params 

    echo 'Yes, it works!'; 

} else { 
    echo 'Invalid parameters!'; 
} 
?> 

O yo tengo un error estúpido o no estoy utilizando el método send() correctamente.

Respuesta

13

Me di cuenta. Necesitaba configurar el encabezado de la solicitud.

xmlhttp.open("POST", "ajax.php", true); 
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
xmlhttp.send("foo=" + foo + "&bar=" + bar); 

source1

source2

Cuestiones relacionadas