1. 程式人生 > >Ajax實現無重新整理表單提交

Ajax實現無重新整理表單提交

  1. 一般方式實現
<!DOCTYPE html>
<html>
    <head>
        <meta charset = "utf-8">
        <title></title>
        <script language = "javascript">
            function f1(){
                //建立xmlHttp物件
                var xmlHttp;
                if(window.ActiveXObject){
                    xmlHttp = new
ActiveXObject("Microsoft.XMLHTTP"); } else if(window.XMLHttpRequest){ xmlHttp = new XMLHttpRequest(); } //獲取表單值 var username = document.form1.username.value; var password = document.form1.password.value; var
email = document.form1.email.value; var datastr = "username=" + username + "&password=" + password + "&email=" + email; var url = "./004.php"; xmlHttp.onreadystatechange = function(){ if(xmlHttp.readyState == 4){ alert(xmlHttp.responseText); } } //提交資料
xmlHttp.open("POST",url,false); xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlHttp.send(datastr); document.getElementById("p1").innerHTML = "表單已提交"; }
</script> </head> <body> <h2>Ajax無重新整理提交表單</h2> <p id="p1"></p> <form name="form1"> <p>使用者名稱:<input type = "text" name = "username" /></p> <p>密碼:<input type = "password" name = "password" /></p> <p>郵箱:<input type = "text" name = "email" /></p> <p><input type = "button" value = "提交" name = "Submit" onclick = "f1()"/></p> </form> </body> </html>

服務端頁面 004.php

//004.php
<?php
//收集form表單傳遞過來的post資訊
print_r($_POST);

執行效果
這裡寫圖片描述

  2.利用FormData表單資料物件,可以實現快速收集表單資訊。FormData是html5的新技術,在主流瀏覽器中都可以正常使用。

<!DOCTYPE html>
<html>
    <head>
        <meta charset = "utf-8">
        <title></title>
        <script language = "javascript">
            function f1(){
                //建立xmlHttp物件
                var xmlHttp;
                if(window.ActiveXObject){
                    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
                }
                else if(window.XMLHttpRequest){
                    xmlHttp = new XMLHttpRequest();
                }

                //獲取表單值
                //利用FormData表單資料物件,快速收集表單資訊
                var form = document.form1;
                var fd = new FormData(form);//收集fm的表單資訊

                //提交資料
                xmlHttp.open("POST","./004.php",false);
                xmlHttp.send(fd);
            }
        </script>
    </head>
    <body>
        <h2>Ajax無重新整理提交表單</h2>
        <form name="form1">
            <p>使用者名稱:<input type = "text" name = "username" /></p>
            <p>密碼:<input type = "password" name = "password" /></p>
            <p>郵箱:<input type = "text" name = "email" /></p>
            <p><input type = "button" value = "提交" name = "Submit" onclick = "f1()"/></p>
        </form>
    </body>
</html>

注意:
(1)FormData要求每個表單域必須有name屬性;
(2)使用FormData的同時不能設定setRequestHeader()方法;
(3)普通表單域的特殊符號無需編碼