AJAX Post表单变量到PHP页面

时间:2014-01-09 11:33:20

标签: javascript php ajax

我有一个执行AJAX函数的表单,用于将表单值提交到PHP页面。 PHP页面只是通过回显DIV中的变量来响应。

它适用于GET方法,但我无法使用POST。

    <html>
    <body>
    <script language="javascript" type="text/javascript">
    <!-- 
    //Browser Support Code
    function ajaxFunction(){
        var ajaxRequest;

        try{
            // Opera 8.0+, Firefox, Safari
            ajaxRequest = new XMLHttpRequest();
        } catch (e){
            // Internet Explorer Browsers
            try{
                ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try{
                    ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e){
                    // Something went wrong
                    alert("Browser Not Supported");
                    return false;
                }
            }
        }
        // Get Response
        ajaxRequest.onreadystatechange = function(){
            if(ajaxRequest.readyState == 4){
                document.getElementById("response").innerHTML = ajaxRequest.responseText;
            }
        }
        var name=document.getElementById("name").value
        var email=document.getElementById("email").value
        ajaxRequest.open("POST", "process.php?name="+name+"&email="+email, true);
        ajaxRequest.send(null); 
    }
    //-->
    </script>
    <form name='Form1'>
      Name:  <input type='text'  name='name' id="name"/> <br />
      Email: <input type='text'  name='email' id="email"/> <br />
    <input type="button" value="Submit" onClick="ajaxFunction();">
    </form>
    <div id="response">
    </div>
    </body>
    </html>

和php页面,process.php

    <?php
    echo date("H:i:s"); 
    echo "<br/>";
    // echo "Post Variables: ".$_POST['name']." ".$POST['email']; old code
            echo "Post Variables: ".$_POST['name']." ".$_POST['email'];
    echo "<br/>";
    echo "Get Variables: ".$_GET['name']." ".$_GET['email'];
    ?>

我得到的回应是:

11时32分05秒 后变量: 获取变量:输入的名称已输入电子邮件

所以我非常确定这是从PHP传递给Javascript的变量。

非常感谢。

1 个答案:

答案 0 :(得分:8)

ajaxRequest.open("POST", "process.php?name="+name+"&email="+email, true);
ajaxRequest.send(null);

那不是发布变量。在这里,您将它们作为GET参数发送,并为您的POST请求提供一个空体。相反,使用

ajaxRequest.open("POST", "process.php", true);
ajaxRequest.send("name="+name+"&email="+email);

甚至更好

ajaxRequest.open("POST", "process.php", true);
ajaxRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
ajaxRequest.send("name="+encodeURIComponent(name)+"&email="+encodeURIComponent(email));