如何在表单中使用Ajax

1、HTML就是一个简单表单验证,有登录按钮,点击登录会发送Ajax,

这里就是简单如果用户名为:zhouzhiruo,密码为:123456,就是登录成功,否则登录失败

应该在发送请求之前对input的value做验证是否符合标准

<form id="myform" name="myform" action="03.php" method="post">
        <table>
            <tr>
                <td>用户名:</td>
                <td><input type="text" id="user" name="user"></td>
            </tr>
            <tr>
                <td>密码:</td>
                <td><input type="password" id="pwd" name="pwd"></td>
            </tr>
            <tr>
                <td></td>
                <td><input type="button" id="btn" value="登录"></td>
            </tr>
        </table>
    </form>

2、JS

//使用Ajax时候不要用subbmit
    var btn=document.getElementById("btn");
    btn.onclick=function(){
        var xhr=getXhr();
        xhr.open('post','03.php');
        xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        var user=document.getElementById("user").value;
        var pwd=document.getElementById("pwd").value;
        xhr.send("user="+user+"&pwd="+pwd);
        xhr.onreadystatechange=function(){
        //获得服务器端当前状态
        //alert(xhr.readyState);
        //保证响应完成
            if(xhr.readyState==4){
                //保证这次请求必须成功
                //alert(xhr.status);
                if(xhr.status==200){
                    //接收服务器端的数据
                    var data=xhr.responseText;
                    //测试
                    console.log(data);
                    }
                }
        }
    };
    function getXhr(){
        var xhr=null;
        if(window.XMLHttpRequest){
            xhr=new XMLHttpRequest();
        }else{
            xhr=new ActiveXObject("Microsoft.XMLHttp");
        }
        return xhr;
    }

3、PHP,链接数据库的语言之一

<?php
    $user=$_POST['user'];
    $pwd=$_POST['pwd'];
    if($user=="zhouzhiruo"&$pwd==
        "123456"){
        echo "login successful";
    }else{
        echo "login error";
    }
?>

 

posted @ 2016-04-19 19:56  逗伴不是瓣  阅读(361)  评论(0编辑  收藏  举报