《Java从入门到放弃》JSP入门篇:XMLHttpRequest的基本用法

作者: java 发布时间: 2017-09-11 浏览: 3177 次 编辑

不闲扯,直接开讲。

使用XMLHttpRequest对象,主要分为以下七个步骤:

  1. 创建对象
  2. 设置过期时间
  3. 设置数据格式
  4. 初始化 HTTP 请求
  5. 设置HTTP头请求
  6. 回传数据的处理
  7. 发送 HTTP 请求

对应代码如下所示

<script type="text/javascript">
    var xhr;
 
    function goAjax() {
    //1.创建对象
    xhr = new XMLHttpRequest();
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
 
    //2.设置过期时间
    xhr.setTimeout = 3000;
    //3.设置数据格式
    xhr.responseType = "text";
    //4.初始化 HTTP 请求参数(未发送)
    xhr.open("POST", "servlet/AjaxLoginServlet", true);
    //5.设置HTTP请求
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    //6.回传数据的处理
    //注册相关事件回调处理函数
    //6.1 回传的数据加载完毕后执行
    xhr.onload = function(e) {
        //alert(this.readyState + "||" + this.status);
        if(this.readyState == 4 || this.status == 200) {
        var div = document.getElementById("divContent");
        div.innerHTML = this.responseText;
                     
        }
    };
    //6.2访问出错
    xhr.onerror = function(e) {
        alert("登录失败!");
    };
    //6.3超时
//  xhr.ontimeout = function(e) {
//  };
    //6.4状态改变
    /* xhr.onreadystatechange = function(e){
            if(this.readyState == 4 || this.status == 200) {
                alert(this.responseText);
            }
    } */
    //7.发送数据
    var username = document.getElementById("username").value;
    var pwd = document.getElementById("password").value;
    xhr.send("username=" + username + "&password=" + pwd);
    }
</script>

HTML页面代码如下:

<body>
    账号:<input type="text" name="username" id="username" /><br />
    密码:<input type="password" name="password" id="password" /><br />
    <input type="button" value="登录" onclick="goAjax();" />
    <div id="divContent" style="width:200px; height: 100px;"></div>
</body>

servlet文件代码如下:

public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    //设置内容格式
    response.setContentType("text/html");
         
    PrintWriter out = response.getWriter();
    //获取url中的用户名和密码
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    //成功输出success 失败输出fail
    if ("haha".equals(username) && "123".equals(password)) {
        out.println("success");
    } else {
        out.println("fail");
    }
    out.flush();
    out.close();
}

本文出自 “软件思维” 博客,请务必保留此出处http://softi.blog.51cto.com/13093971/1950888