2011-08-15 8 views
6

데이터를 PHP 페이지에 게시하고 응답을 확인하려고합니다. 다음은 그 예입니다. 이 코드의 문제점은 무엇입니까?매개 변수가있는 XMLHttp의 POST

<?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!'; 
} 
?> 

어느 ajax.php 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> 

나는 바보 같은 오타가 있거나 내가 제대로 송신() 메소드를 사용하고 있지 않다.

답변

13

나는 그것을 알아 냈다. 요청 헤더를 설정해야했습니다.

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

source1

source2

관련 문제