原生Ajax基础操作

原生Ajax基础操作

Ajax(Asychronous JavaScript And XML)即异步的JavaScript与XML,其本质是一种局部刷新技术。
Ajax
Ajax的使用主要是依靠“XMLHttpRequest"对象,如果想创建这个对象则还要考虑到不同浏览器的兼容问题。

    var xmlHttpRequest;//表示Ajax的主要处理对象
    function create(){//函数功能为创建XMLHttpRequest对象
        if(window.XMLHttpRequest){//当前浏览器不是IE
            xmlHttpRequest = new XMLHttpRequest();//直接创建对象
        }else{//如果是IE浏览器,则需要通过ActiveX进行对象创建
            xmlHttpRequest = new ActiveXObject("Microsoft.XMLHttp");
        }
    }

XMLHttpRequest对象中的方法

No方法名描述
1abort()取消当前所发出的请求
2getAllResponseHeaders()取得所有的Http头信息
3getResponseHeader()取得一个指定的Http头信息
4open()创建一个Http请求,并指定模式(Post请求或Get请求)
5send()将创建的请求发送到服务器端,并接收回应信息
6setRequestHeader()设置一个指定请求的Http头信息

XMLHttpRequest对象中的属性

No属性描述
1onreadystatechange指定当readyState状态改变时使用的属性,一般都用于指定具体的回调函数
2readyState返回当前的请求状态,只读
3responseBody将回应信息正文以unsigned byte数组形式返回,只读
4responseStream以Ado Stream对象的形式返回响应信息,只读
5responseText接收以普通文本返回的数据,只读
6responseXML接收以XML文档形式回应的数据,只读
7status返回当前请求的http状态码,只读
8statusText返回当前请求的相应行状态,只读

我们通过readyState和status的值来判断Ajax处理状态,如果服务器端处理成功status的值为200,如果出现了其他错误,则status可能是4xx或5xx,也就是说只要status的值不是200就永远是错的。
readyState共有5种取值

NoreadyState值描述
10请求没有建立(表示调用open()函数之前的状态)
21请求已经建立但没有发出(表示调用send()函数之前的状态)
32请求已经发出正在处理中
43请求已经处理,正在接收服务器的信息(服务器还没有完成响应)
54响应已完成,可以访问服务器响应并使用它
ECHO交互

1.新建一个EchoServlet,用来输出服务器信息

package com.ajax.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;

@WebServlet(urlPatterns = "/EchoServlet/*")
public class EchoServlet extends HttpServlet {
    private HttpServletRequest request;
    private HttpServletResponse response;

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.request = request;
        this.response = response;
        String methodName = request.getRequestURI().substring(request.getRequestURI().lastIndexOf("/")+1);
        try{
            Method method = this.getClass().getMethod(methodName);
            method.invoke(this);
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    public void echo(){
        try {
            this.request.setCharacterEncoding("UTF-8");
            this.response.setCharacterEncoding("UTF-8");
            this.response.setContentType("text/html");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String message = this.request.getParameter("msg");
        try {
            this.response.getWriter().print(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

1.新建一个echo.jsp页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page pageEncoding="UTF-8" %>
<%
    String basePath = request.getScheme()+"://"+request.getServerName()
            +":"+request.getServerPort()+request.getContextPath();
    String echoPath = basePath+"/EchoServlet/echo";
%>
<html>
<head>
    <title>Echo</title>
</head>
<body>
<div>
    信息:<input type="text" id="msg" name="msg" />
    <input type="button" id="sendBut" value="发送" /><br>
    echo:<br>
    <div id="echoMsg">
        <span>此处显示回应信息......</span>
    </div>
</div>
<script type="text/javascript">
    var xmlHttpRequest;//表示Ajax的主要处理对象
    function create(){//函数功能为创建XMLHttpRequest对象
        if(window.XMLHttpRequest){//当前浏览器不是IE
            xmlHttpRequest = new XMLHttpRequest();//直接创建对象
        }else{//如果是IE浏览器,则需要通过ActiveX进行对象创建
            xmlHttpRequest = new ActiveXObject("Microsoft.XMLHttp");
        }
    }
    window.onload = function(){
        document.getElementById("sendBut").addEventListener("click",function(){
            //接收用户输入的msg的内容
            var msg = document.getElementById("msg").value;
            if(msg!=""){//如果用户输入不为空
                create();
                //设置Ajax请求方式及服务器端接收地址
                xmlHttpRequest.open("post","<%=echoPath%>?msg="+msg);
                xmlHttpRequest.send(null);//发送请求到open()设置的路径之中
                xmlHttpRequest.onreadystatechange = function(){//处理数据返回来的回调函数
                    if(xmlHttpRequest.readyState==2||xmlHttpRequest.readyState==3){//传输未完成
                        window.console.log("等待......");
                    }
                    if(xmlHttpRequest.readyState==4){
                        if(xmlHttpRequest.status==200){//处理完毕
                            var echoMsgEle = document.getElementById("echoMsg");
                            var spanEle = document.createElement("span");
                            spanEle.appendChild(document.createTextNode(xmlHttpRequest.responseText));
                            echoMsgEle.appendChild(document.createElement("br"));
                            echoMsgEle.appendChild(spanEle);
                        }
                    }
                }
            }
        },false);
    }
</script>
</body>
</html>

3.通过页面发送信息,发现服务器返回正常

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值