如何实现AJAX 的异步功能

js教程评论818 views阅读模式

本文给大家分享的是如何实现AJAX的异步功能,非常的详细,也很实用,适合JavaScript的初学者,有需要的小伙伴参考下。

关于AJAX异步功能的小实验

为了实验ajax的异步

性,先建一个Web项目,结构大概是这个样子

360截图20180408171612437.jpg

TestServlet.java(主要是提供ajax后台调用的程序)

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class TestServelet
 */
 @WebServlet("/TestServelet")
 public class TestServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
     /**
     * Default constructor. 
     */
    public TestServlet() {
    }    
    
    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        
    //为了体现程序的异步性,先让它睡3s
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        response.setCharacterEncoding("utf-8");  
        //打印出程序运行的时间
        System.out.println("异步程序运行时间:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS") .format(new Date()));
    }    
    
    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

testAjax.jsp(前台页面和js,触发异步调用)

<%@ page language="java" contentType="text/html;charset=UTF-8" %>
<html >
<head></head>
<body onload="testajax()">
    Hello Ajax!<br>
</body>
</html>
<SCRIPT LANGUAGE="JavaScript">
    function testajax(){
        fnGetAjaxReturn('http://localhost:8080/TestProject/TestServlet?a='+Math.random());
    }    
    
    function fnGetAjaxReturn(url)
    {   
        var userAgent = navigator.userAgent;        
        var http_request = false;        
        //开始初始化XMLHttpRequest对象
        if(window.XMLHttpRequest) { //Mozilla 浏览器
            http_request = new XMLHttpRequest();            
            if (http_request.overrideMimeType) {//设置MiME类别
                http_request.overrideMimeType("text/xml");
            }
        }        
        //else if (window.ActiveXObject) { // IE浏览器
        else if (window.ActiveXObject||userAgent.indexOf("Trident") > -1){          
           try {
                http_request = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {                try {
                    http_request = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {alert("错了吧");}
            }
        }        if (!http_request) { // 异常,创建对象实例失败
            window.alert("不能创建XMLHttpRequest对象实例.");            
            return false;
        }
        http_request.open("GET", url, true);//true 异步  false 同步 
        http_request.send();
        alert("异步请求之后执行时间:"+new Date +'\n毫秒数:'+ new Date().getMilliseconds());
    }</script>

说明:jsp页面加载之后调用一个js,js中会先发出一个异步请求,再执行一个alert弹出操作。


下面开始试验

用IE浏览器,运行URL
http://localhost:8080/TestProject/testAjax.jsp

发现,程序先弹出了alert,过了3s钟,ajax才返回了后台结果,充分证明了ajax的异步性。

运行结果:

360截图20180408172134306.jpg

从时间的差异性,发现程序先执行结束(执行了alert),过了3s钟,异步程序才返回结果。


反过来,如果把jsp文件中的

http_request.open("GET", url, true);

true 改为 false 呢?

运行URL,发现程序在苦苦等待Servlet后台请求返回之后,才执行了js中的最后一段代码alert,正是所谓的同步调用。

运行结果如下:

360截图20180408172210037.jpg

The end!

以上就是如何实现AJAX 的异步功能的详细内容,更多请关注php教程其它相关文章!

企鹅博客
  • 本文由 发表于 2020年8月30日 04:19:40
  • 转载请务必保留本文链接:https://www.qieseo.com/398415.html

发表评论