Ajax(一)

来源:互联网 发布:three.js 360度全景 编辑:程序博客网 时间:2024/06/11 20:57

JavaScript对象XMLHttpRequest

常用方法和说明

  1. open(method,URL,async)
    建立与服务器的连接
    method参数指定请求的HTTP方法,典型的值是GET或POST
    URL参数指定请求的地址
    async参数指定是否使用异步请求,其值为true或false

  2. send(content)
    发送请求
    content参数指定请求的参数

  3. setRequestHeader(header,value)
    设置请求的头信息

常用属性

  1. onreadystatechange:指定回调函数

  2. readystate:XMLHttpRequest的状态信息
    就绪状态码和状态说明:
    0:XMLHttpRequest对象没有完成初始化
    1:XMLHttpRequest对象开始发送请求
    2:XMLHttpRequest对象的请求发送完成
    3:XMLHttpRequest对象开始读取响应,还没有结束
    4:XMLHttpRequest对象读取响应结束

  3. status:HTTP的状态码
    状态码和状态说明:
    200:服务器响应正常
    400:无法找到请求的资源
    403:没有访问权限
    404:访问的资源不存在
    500:服务器内部错误

  4. responseText:获得响应的文本内容

  5. responseXML:获得响应的XML文档对象


代码如下

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <title>My JSP 'index.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="This is my page">    <!--    <link rel="stylesheet" type="text/css" href="styles.css">    -->    <script type="text/javascript">        function userNameValidate(){            var userName = document.getElementById("userName").value;            var xmlHttp = null;            // 浏览器的兼容性            try {                xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");            }catch(e){                try{                    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");                }catch(e){                    xmlHttp = new XMLHttpRequest();                 }            }            // 设置打开的方式及页面            xmlHttp.open("post", "UserValidate?userName="+userName, true);            xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");            // 指定回调过来的函数            xmlHttp.onreadystatechange=function(){                if(xmlHttp.readyState==4){                    // 4 已经正常响应完成的情况                    if(xmlHttp.status==200){                        // 200 代表服务器一切正常                        var str=xmlHttp.responseText; // 将服务器返回的信息保存到str中                        document.getElementById("nameValidateReturn").innerHTML=str;                                }                }            };            xmlHttp.send(null);        }        function userPasswordValidate(){            var userPassword = document.getElementById("userPassword").value;            var xmlHttp = null;            // 浏览器的兼容性            try {                xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");            }catch(e){                try{                    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");                }catch(e){                    xmlHttp = new XMLHttpRequest();                 }            }            // 设置打开的方式及页面            xmlHttp.open("post", "UserValidate", true);            xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");            // 指定回调过来的函数            xmlHttp.onreadystatechange=function(){                if(xmlHttp.readyState==4){                    // 4 已经正常响应完成的情况                    if(xmlHttp.status==200){                        // 200 代表服务器一切正常                        var str=xmlHttp.responseText; // 将服务器返回的信息保存到str中                        document.getElementById("passwordValidateReturn").innerHTML=str;                                }                }            };            xmlHttp.send("userPassword="+userPassword);        }        function userIsNull(){            var userName = document.getElementById("userName").value;            var userPassword = document.getElementById("userPassword").value;            if(userName == ""){                alert("请输入用户名!");                return false;            }            if(userPassword == ""){                alert("请输入密码!");                return false;            }            var nameValidateReturn = document.getElementById("nameValidateReturn").innerHTML;            var passwordValidateReturn = document.getElementById("passwordValidateReturn").innerHTML;            if(nameValidateReturn == "ok"){                if(passwordValidateReturn =="ok"){                    alert("登陆成功!");                    return true;                }else{                    alert(passwordValidateReturn);                    return false;                }            }else{                alert(nameValidateReturn);                return false;            }        }    </script>  </head>  <body>    <form action="#" method="post" onsubmit="return userIsNull();">        <table cellspacing="15">            <tr>                <td>用户名:</td>                <td><input type="text"  id="userName" onblur="userNameValidate()" /></td>                <td><span id="nameValidateReturn" style="color:#EE7621;"></span></td>            </tr>            <tr>                <td align="right">密码:</td>                <td><input id="userPassword" type="password" onblur="userPasswordValidate()"></td>                <td><span id="passwordValidateReturn" style="color:#EE7621;"></span></td>            </tr>            <tr>                <td align="center" colspan="2">                    <input id="login" value="登陆" type="submit" class="login_btn">                </td>                <td></td>            </tr>        </table>    </form>  </body></html>

UserValidate.java

package com.doris.ajax.servlet;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class UserValidate extends HttpServlet {    @Override    protected void doPost(HttpServletRequest req, HttpServletResponse resp)            throws ServletException, IOException {        // TODO Auto-generated method stub        // 获取用户名和密码        String userName = req.getParameter("userName");        String userPassword = req.getParameter("userPassword");        System.out.println(userName);        System.out.println(userPassword);        resp.setContentType("text/html;charset=utf-8");        PrintWriter out = resp.getWriter();        String validateReturn = "";        if (userName != null && userName.length() > 0) {            // 中文乱码            userName=new String(userName.getBytes("ISO-8859-1"),"GBK");            System.out.println(userName);            if(userName.equals("admin") || userName.equals("pccc"))                validateReturn = "ok";            else                validateReturn = "用户不存在!";        }         if (userPassword != null && userPassword.length() > 0) {            if(userPassword.equals("admin") || userPassword.equals("pccc"))                validateReturn = "ok";            else                validateReturn = "密码错误!";        }         // 将服务器的处理信息 输出给客服端        out.write(validateReturn);        out.flush();        out.close();    }    @Override    protected void doGet(HttpServletRequest req, HttpServletResponse resp)            throws ServletException, IOException {        // TODO Auto-generated method stub        doPost(req, resp);    }}
0 0
原创粉丝点击