欢迎加入QQ讨论群258996829
麦子学院 头像
苹果6袋
6
麦子学院

Ajax技术实现服务端客户端异步通信原理详解

发布时间:2016-09-28 16:38  回复:0  查看:2447   最后回复:2016-09-28 16:38  

AJAX客户端与服务端,可以在[不刷新整个浏览器]的情况下,与服务器进行异步通信的技术。即ajax是一个[局部刷新]的异步通信技术,AJAX技术不是全新的语言,时2005年谷歌公司提出的一种全新的编程模式,不是新的编程语言。

 

传统web应用请求和响应的特点


( 1 )请求:浏览器以 HTTP 协议的方式提交请求到服务器

 

( 2 )响应:服务器以 HTTP 协议的方式响应内容到浏览器

 

注意: HTTP 是 WEB 大众化非安全协议

 

HTTPS 是 WEB 安全协议,是基于 HTTP 协议的,且加了一些加密等特殊功能,常用于在线支付,或者是需要安全性较高的网站中,例如: 12306 网站

 

HTTP 请求有三个部份组成:请求行,请求头,请求体

 

HTTP 响应有三个部份组成:响应行,响应头,响应体

 

( 3 )状态栏:有明显的进度条刷新现象,如果服务器响应较慢的话,进度条刷新也会变慢, IE9 等中高版本浏览器,有明显转圈圈图标

 

( 4 )历史栏:会收集原来已访问过的 web 页面,进行缓存

 

( 5 )缺点:不需变化的大量数据,也全部刷新,造成浏览器加载和处理负担

 

( 6 )可改进的地方:让不需变化的大量数据,原封不动,不用缓存到历史栏中,无需全部刷新,只刷新某些需要变化的数据区域.

 

ajax异步获取时间的实例

 

<%--

  Created by IntelliJ IDEA.

  User: cxspace

  Date: 16-8-16

  Time: 上午8:33

  To change this template use File | Settings | File Templates.

--%>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

    <title>无需刷新整个web页面显示服务器响应时间</title>

</head>

<body>

   当前时间

     <span id = "time"></span> <br>

 

   <input id="buttonID" type="button" value="获取当前时间">

 

   <br>

 

    <script type="text/javascript">

 

        //创建ajax对象

        function createAJAX() {

 

            var ajax = null;

 

            try {

                ajax = new ActiveXObject("microsoft.xmlhttp");

 

            }catch (e1){

 

                try {

                    ajax = new XMLHttpRequest();

                }catch (e2){

 

                    alert("你的浏览器不支持异步对象,请更换浏览器");

                }

 

            }

 

            return ajax;

        }

 

 

    </script>

 

    <script type="text/javascript">

 

        document.getElementById("buttonID").onclick = function () {

/1.创建ajax异步对象

            var ajax = createAJAX();

            //2.准备发送请求

            var method = "GET";

            var url = "${pageContext.request.contextPath}/AjaxTimeServlet?time="+new Date().getTime();

            ajax.open(method,url);

            //3.真正发送请求体数据到服务器,如果请求体中没有内容,null表示

            ajax.send(null);

 

            //==========等待

 

 

            //4.ajax异步对象不断监听服务器的状态0-1-2-3-[4]

            // 一定要状态变化后,才触发function函数

            // 如果状态永远时4-4-4-4-4,不会触发function(){}函数

            ajax.onreadystatechange = function () {

                //如果状态码是4

                if (ajax.readyState == 4){

                    //如果响应码是200

                    if (ajax.status == 200){

                        //5.用ajax异步对象中获取数据

                        var nowStr = ajax.responseText;

                        var spanElement = document.getElementById("time");

                        spanElement.innerHTML = nowStr;

 

                    }

                }

 

            }

 

        }

 

 

    </script>

 

 

</body>

 

</html>

package 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.PrintWriter;

import java.text.SimpleDateFormat;

import java.util.Date;

 

/**

 * Created by cxspace on 16-8-16.

 */

 

public class AjaxTimeServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String nowStr = sdf.format(new Date());

 

       // System.out.println("拿到时间");

        //以流的方式响应到ajax异步对象中

        response.setContentType("text/html;charset=UTF-8");

        PrintWriter pw = response.getWriter();

        pw.write(nowStr);

        pw.flush();

        pw.close();

    }

 

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        doPost(request,response);

    }

}

什么是 AJAX 【 Asynchronous 异步的 JS 和 XML 】,工作原理与特点

 

( 1 )什么是同步:

 

请求 1-> 响应 1-> 请求 2-> 响应 2->

 

Web1.0 时代

 

( 2 )什么是异步:

 

请求 1-> 请求 2-> 请求 3-> 响应 1-> 响应 2-> 响应 3->

 

请求 1-> 响应 1-> 请求 2-> 请求 3-> 响应 2-> 响应 3->

 

Web2.0 时代

 

项目中: Web1.0 为主(整个浏览器刷新), Web2.0 为辅(浏览器局部刷新)

 

( 3 )什么是 AJAX

 

客户端(特指 PC 浏览器)与服务器,可以在【不必刷新整个浏览器】的情况下,与服务器进行异步通讯的技术

 

即, AJAX 是一个【局部刷新】的【异步】通讯技术

 

AJAX 不是全新的语言,是 2005 年 Google 公司推出的一种全新【编程模式】,不是新的编程语言

 

( 4 )不用刷新整个页面便可与服务器通讯的办法有:

 

( A ) Flash/ActionScript

 

( B )框架 Frameset

 

( C ) iFrame (内嵌入框架 )

 

( D ) XMLHttpRequest( 非 IE 浏览器 和 ActiveXObject(IE 浏览器 )

 

背景:早上 IE5 时,微软就开发出了第一个异步通讯对象,叫 ActiveXObject 对象,

 

Firefox 等其它浏览器厂商也慢慢引入异步通讯对象,叫 XMLHttpRequest 对象,

 

IE 的高版本,也将这个异步对象取名叫 XMLHttpRequest 对象,但 IE 有向下兼容问题,

 

也可以使用 ActiveXObject 对象。

 

无需第三方 jar 包,现代中高版本浏览器中内置了这个异步通讯对象,只需通过 JavaScript 就可以创建

 

注意:所有浏览器中都内置了异步对象,在默认情况下,该异步对象并没有创建出来

 

function createAJAX(){

 

var ajax = null;

 

try{

ajax = new ActiveXObject("microsoft.xmlhttp");

 

}catch(e1){

 

ajax = new XMLHttpRequest();

 

}

 

return ajax;

 

}

( 5 ) AJAX 工作原理

Ajax技术实现服务端客户端异步通信原理详解

( 6 ) AJAX 包含的技术

Ajax技术实现服务端客户端异步通信原理详解


( 7 ) AJAX 开发步骤

 

步一:创建 AJAX 异步对象,例如: createAJAX()

 

步二:准备发送异步请求,例如: ajax.open(method,url)

 

步三:如果是 POST 请求的话,一定要设置 AJAX 请求头,例如: ajax.setRequestHeader()

 

如果是 GET 请求的话,无需设置设置 AJAX 请求头

 

步四:真正发送请求体中的数据到服务器,例如: ajax.send()

 

步五: AJAX 不断的监听服务端响应的状态变化,例如: ajax.onreadystatechange ,后面写一个无名处理函数

 

步六:在无名处理函数中,获取 AJAX 的数据后,按照 DOM 规则,用 JS 语言来操作 Web 页面

 

( 8 ) AJAX 适合用在什么地方

 

AJAX 【适合】不用来传递大量数据,而只用来【传递少量数据】,在用户的【体验】上,【更加人性化】

 

AJAX 是一个和服务器无关的技术,即服务器可使用: JavaEE , .NET , PHP ,。。。这些技术都可

 

AJAX 只管向服务器发送请求,同时只管接收服务器的 HTML 或 XML 或 JSON 载体响应

 

服务端不能使用转发或重定向到 web 页面,因为这样会起浏览器全面刷新

 

即只能以流的方式响应给浏览器

 

AJAX异步方式实现验证实例(GET方式)

 

<%--

  Created by IntelliJ IDEA.

  User: cxspace

  Date: 16-8-16

  Time: 下午7:15

  To change this template use File | Settings | File Templates.

--%>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>

<head>

    <title>以get方式异步检查数据库中是否已经存在该用户</title>

</head>

<body>

    <form>

        用户名:<input id="usernameID" type="text" name="username"/>

        光标移出后立即检查结果

    </form>

 

    <hr>

 

    <span id="resID"></span>

 

 

 

    <script type="text/javascript">

 

        function createAJAX() {

 

            var ajax = null;

 

            try {

 

                ajax = new ActiveXObject("microsoft.xmlhttp");

 

            }catch (e1){

 

                try {

 

                    ajax = new XMLHttpRequest();

 

                }catch (e2){

 

                    alert("你的浏览器不支持ajax,请更换浏览器")

 

                }

            }

            return ajax;

        }

 

    </script>

 

    <script type="text/javascript">

 

        document.getElementById("usernameID").onblur = function () {

 

            var username = this.value;

 if(username.length == 0){

                document.getElementById("resID").innerHTML = "用户名必填";

            }else {

 

                username = encodeURI(username);

 

               // alert(username)

 

                var ajax = createAJAX();

 

            //    alert("创建ajax ok")

 

                var method = "GET";

 

                var url="${pageContext.request.contextPath}/UserServlet?time="+new Date().getTime()+"&username="+username;

 

                ajax.open(method,url);

 

                ajax.send(null);

 

                ajax.onreadystatechange = function () {

                    if (ajax.readyState == 4){

 

                        if (ajax.status == 200){

 

                            var tip = ajax.responseText;

 

                            document.getElementById("resID").innerHTML = tip;

 

                        }

 

                    }

                }

 

            }

 

        }

 

    </script>

 

</body>

</html>

package 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.PrintWriter;

 

/**

 * Created by cxspace on 16-8-16.

 */

 

public class UserServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

 

        doGet(request,response);

 

    }

 

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

 

        request.setCharacterEncoding("utf-8");

 

        String username = request.getParameter("username");

 

        System.out.println(username);

 

        String tip = "<font color='green'> 可以注册 </front>";

 

        if ("杰克".equals(username)){

            tip = "<font color='red'> 该用户已经存在 </front>";

        }

 

        response.setContentType("text/html;charset=UTF-8");

 

        PrintWriter pw = response.getWriter();

 

        pw.write(tip);

 

        pw.flush();

 pw.close();

 

    }

}

以POST的方式实现异步验证实例

 

注意点:content中键值对表达式绝对不能有空格

 

<%--

  Created by IntelliJ IDEA.

  User: cxspace

  Date: 16-8-17

  Time: 上午9:37

  To change this template use File | Settings | File Templates.

--%>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>

<head>

    <title>以post方式验证检查注册的用户名是否在数据库中存在</title>

 

    <script type="text/javascript"  src="js/ajax.js"></script>

</head>

<body>

   用户名[POST]: <input id="usernameID" type="text" />

 

   <span id="resID">

 

 

   </span>

 

   <hr/>

 

   <script type="text/javascript">

 

       document.getElementById("usernameID").onblur = function () {

 

           var username = this.value;

 

         //  alert(username);

 

           var ajax = createAJAX();

 

           var method = "POST";

 var url = "${pageContext.request.contextPath}/UserServlet?time="+new Date().getTime();

 

           ajax.open(method,url);

 

           //设置ajax请求头为post,他会将请求体中的汉字自动进行utf-8的编码

           ajax.setRequestHeader("content-type","application/x-www-form-urlencoded");

 

 

           //******键值对中间不能有空格,例如 username = aa; 服务端拿到为null

 

           var content = "username="+ username;

 

           ajax.send(content);

 

           //wait

           ajax.onreadystatechange = function () {

 

               if (ajax.readyState == 4){

 

                   if (ajax.status == 200){

 

                       var tip = ajax.responseText;

 

                       var imgElement = document.("img");

 

                       imgElement.src = tip;

                       imgElement.style.width="12px";

                       imgElement.style.height="12px";

 

                       var spanElement = document.getElementById("resID");

 

                       spanElement.innerHTML = "";

 

                       spanElement.appendChild(imgElement);

 

                   }

 

               }

 

           }

 

       }

</script>

 

</body>

</html>

package servlet;

 

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

import java.io.PrintWriter;

 

/**

 * Created by cxspace on 16-8-16.

 */

 

public class UserServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

 

        request.setCharacterEncoding("UTF-8");

 

        String username = request.getParameter("username");

 

     //   System.out.println(username);

 

        String tip = "images/MsgSent.gif";

 

        if ("杰克".equals(username)){

            tip = "images/MsgError.gif";

        }

 

        System.out.println(tip);

 

        response.setContentType("text/html;charset=UTF-8");

        PrintWriter pw = response.getWriter();

        pw.write(tip);

        pw.flush();

        pw.close();

 

    }

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

 

        request.setCharacterEncoding("utf-8");

 

        String username = request.getParameter("username");

 

        System.out.println(username);

 

        String tip = "<font color='green'> 可以注册 </front>";

 

        if ("杰克".equals(username)){

            tip = "<font color='red'> 该用户已经存在 </front>";

        }

 

        response.setContentType("text/html;charset=UTF-8");

 

        PrintWriter pw = response.getWriter();

 

        pw.write(tip);

 

        pw.flush();

 

        pw.close();

 

    }

}

 

文章来源:博客园

您还未登录,请先登录

热门帖子

最新帖子