Ajax状态码

<form action="#" method="post">    
    <input type="text" name="username" id="username"/>
    <input type="password" name="password" id="password"/>
    <input type="button" onclick="loginAjax()" value="ajax登录"/>
</form>



<script type="text/javascript">
    /*
        
        XMLHttpRequest i8+ 你口中所说的ajax
        它是构建HTTP请求的javascript对象,在早期它是ActiveX对象形式存在,
        服务器端和客户端数据传递过程异步的问题,早期数据的传递一个字符串一个xml
        实际上,ajax就是在javascript和xml之间创建一种异步传输的方式

        xml:为何出现xml文档格式:
        一种有格式方便进行管理和解析

        它只不过是另一种Http请求而已,它和form表单原理是同样,只不过不会刷新页面进行一种异步的交互
    */

    function loginAjax(){
        var username = document.getElementById("username").value;
        var password = document.getElementById("password").value;
        var params = "username="+username+"&password="+password;
        //建立一个(ajax)xhr对象
        var xhr = new XMLHttpRequest();
        //true代码的是异步请求,执行成功和失败回调函数
        //请求的状态, readyState 
        //0:未初始化状态
        //1:载入请求的状态
        //2:载入完成状态
        //3:请求交互状态
        //4:请求完成状态


        //能够捕获服务器错误,知识点:status
        //500 服务器链接失败 ---服务器关闭
        //404 表明页面找到
        //400 Bad Request请求语法。url写错了,请求地址有问题
        //405 请求方式有问题 springmvc  methpd=RequestMethod.POST
        //200 表明交互成功,正确请求和响应
        xhr.onreadystatechange = function(){
            //ajax载入完成和服务器没错误
            if(this.readyState == 4 && this.status ==200){
                alert(this.responseText)
            }
        };
        //请求方式:post/get
        //get请求的方式以下:
        //xhr.open("get","http://localhost/keke_ajaxtest/xiaojie.jsp"+params,true);
        //xhr.send();
        //post请求的方式以下:
        xhr.open("post","http://localhost/keke_ajaxtest/xiaojie.jsp",true);
        xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
        xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded;"); 
        //发送数据,若是请求方式是post话send必定要设置参数
        xhr.send(params);//发送
    };

    /*
    <form action="http://localhost/keke_ajaxtest/xiaojie.jsp" method="post">    
        <input type="text" name="username"/>
        <input type="text" name="password"/>
        <input type="submit" value="form登录"/>
    </form>*/
    
</script>
相关文章
相关标签/搜索