java web开发:ajax技术(一)——局部刷新技术的实现

一 什么是Ajax

Ajax:AsynchronousJavaScript And Xml——异步JavaScript和XML技术,还有一个比较通用的名称:页面局部刷新技术;是一种把多种技术融合到一起的JavaScript框架之一

二 Ajax主要用在哪里

Ajax的局部刷新是应用相对比较广泛的功能之一

比如常见搜索引擎的搜索建议(如在百度搜索页面中输入具体的字符后弹出匹配的关键词等等)、Google Maps(只刷新网页中地图所在的区域)、网页数据的验证(如账号等是否已经被注册或者使用)等等

三 怎么使用Ajax

(1)掌握Ajax技术,需要对一下内容有足够的了解

——标准web页面开发技术:HTML + CSS

——使用DOM模型解析HTML/XML的技术

——使用XMLHttpRequest对象(Ajax的核心,也是要讲解的重点)

——服务端编程技术:JSP/SERVLET

(2)实现一个简单Ajax程序的固定步骤

(2.1)创建XMLHttpRequest对象

*  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *

// 1. 声明变量,获取一个XMLHttpRequest对象(固定写法)
            var xmlHttp;
            try {
                xmlHttp = new XMLHttpRequest();        
            } catch (e) {
                try {
                    xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");                    
                } catch (e) {
                    try {
                        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");                        
                    } catch (e) {
                        alert("您的浏览器不支持AJAX,请更新浏览器版本");
                    }
                }
            }

*  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *

(2.2)创建处理服务器响应数据的代码

*  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *

// 2. 处理服务器响应回来的数据(固定写法)
            xmlHttp.onreadystatechange = function () {

                   /*  *  *  *  *  *  *  *  *  *  *  *  *  *  *  自主开发部分 *  *  *  *  *  *  *  *  *  *  *  *  *  *  **/       

                  }

            };

*  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *

(2.3)按照指定的方式打开和服务器之间的连接

*  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *

// 3. 打开远程连接
 xmlHttp.open("method", "url", async);

参数解析

method:post/get——提交请求的方法

url——提交到服务器的url地址

async:true/false——是否异步提交

*  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *

(2.4)发送请求

*  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *
 xmlHttp.send(null);

*  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *

四 Ajax提交请求的两种方式

(1) GET方法提交异步请求

*  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *

xmlHttp.open("get", "helloajax.action", true);

*  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *

示例:客户密码拾取器

a. servlet

~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~

package com.phome.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AjaxServlet extends HttpServlet{

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        System.out.println("服务器接受到了请求...");
        String password = req.getParameter("password");
        System.out.println("客户端输入的密码:" + password);
    }
    
}

~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~

b. web.xml配置

~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>ajax_0100</display-name>
  <!-- 1. 第一个ajax程序:密码拾取器 -->
  <servlet>
      <servlet-name>ajaxservlet</servlet-name>
      <servlet-class>com.phome.servlet.AjaxServlet</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>ajaxservlet</servlet-name>
      <url-pattern>/helloajax.action</url-pattern>
  </servlet-mapping>

  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~

c. 视图页面开发——index.jsp

~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~

<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <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 chkInput (value) {
            var xmlHttp = new XMLHttpRequest;
            
            xmlHttp.open("get", "helloajax.action?password=" + value, true);
            xmlHttp.send(null);
        }
    </script>
    
  </head>
 
  <body>
    <!--  baidu: <input type="text" name="text" οnkeyup="chkInput()" /><br /> -->
    password : <input type="password" name="password" οnblur="chkInput(this.value)"/><br />
  </body>
</html>

~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~

d. 测试

~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~

运行项目

打开浏览器访问页面主页

在密码输入框中输入密码

服务器端会打印出用户输入的具体密码字符

~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~   ~

(2)post方法体提交异步请求

将上例中视图页面中的发送请求部分修改为下面的post方式发送请求格式

*  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *

// 4. 发送请求
            xmlHttp.setRequestHeader("Content-Type" , "application/x-www-form-urlencoded");
            xmlHttp.send(null);

*  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *

五 Ajax参数传递

(1)get方法提交参数

get方法提交参数,只需要在XMLHttpRequest.open();方法中,将参数附加到Url地址的后面即可

如:xmlHttp.open("get", "helloajax.action?password=" + value, true);

(2)post方法提交参数

post方法提交参数

a.设置请求头,告诉服务器参数包含在Post表单中提交

xmlHttp.setRequestHeader("Content-Type" , "application/x-www-form-urlencoded");

b. 在发送请求时附加参数传递

如:

xmlHttp.setRequestHeader("Content-Type" , "application/x-www-form-urlencoded");
xmlHttp.send("username=" + value);

六 Ajax处理服务器响应数据的方法

Ajax可以处理服务器返回的数据,主要有以下几种

(1)普通文本数据

(2)XML数据

(3)JSON数据——现下最流行的Ajax数据传递格式,详细JSON教程后续发布

示例:模拟用户信息查看器——JSON数据传递

*  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *

a. 控制器servlet开发

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

package com.phome.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;

import com.phome.model.Address;
import com.phome.model.User;

public class AjaxServlet3 extends HttpServlet{

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        
        req.setCharacterEncoding("gb18030");
        resp.setContentType("text/html;charset=gb18030");
        
        
        
        System.out.println("服务器接受到了请求...");

        String username = req.getParameter("username");
        System.out.println("客户端输入的账号:" + username);
        
        User user = null;
        Address addr = null;
        if ("admin".equals(username)) {
            user = new User("admin" , "admin" , 23 , "男" , addr);
        } else if("manager".equals(username)) {
            user = new User("manager" , "manager" , 33 , "女");
        }
        
        PrintWriter out = resp.getWriter();// 获取到浏览器的输出流
        //out.write("{username:" + user.getUsername() + ",password:******,age:" + user.getAge() + ",gender:" + user.getGender() +"}");
        out.write("{\"username\":\"" + user.getUsername() + "\",\"password\":\"******\",\"age\":\"" + user.getAge() + "\",\"gender\":\"" + user.getGender() +"\"}");
        out.flush();
        out.close();
    }
    
}


~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

b. web.xml配置

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">

  <display-name>ajax_0100</display-name>


<!-- 使用json完成用户信息查看功能 -->
  <servlet>
      <servlet-name>ajaxservlet3</servlet-name>
      <servlet-class>com.phome.servlet.AjaxServlet3</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>ajaxservlet3</servlet-name>
      <url-pattern>/helloajax3.action</url-pattern>
  </servlet-mapping>
 

  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

c. 视图开发

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <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 chkInput (value) {
            // 1. 声明变量,获取一个XMLHttpRequest对象(固定写法)
            var xmlHttp;
            try {
                xmlHttp = new XMLHttpRequest();        
            } catch (e) {
                try {
                    xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");                    
                } catch (e) {
                    try {
                        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");                        
                    } catch (e) {
                        alert("您的浏览器不支持AJAX,请更新浏览器版本");
                    }
                }
            }
            
            // 2. 处理服务器响应回来的数据(固定写法)
            xmlHttp.onreadystatechange = function () {
                // readyState状态为4时,表示请求已经成功响应
                if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                    // 获取服务器端响应的数据
                    var result = xmlHttp.responseText;
                    //alert(typeof(xmlHttp.responseText));
                    //$("username").innerText = xmlHttp.responseText;
                    var userinfo = eval("("+result+")");
                    //alert(userinfo);
                    
                    $("username").innerText = userinfo.username;
                    $("password").innerText = userinfo.password;
                    $("age").innerText = userinfo.age;
                    $("gender").innerText = userinfo.gender;
                }
            };
            
            // 3. 打开远程连接
            xmlHttp.open("post", "helloajax3.action", true);
            // 4. 发送请求
            xmlHttp.setRequestHeader("Content-Type" , "application/x-www-form-urlencoded");
            xmlHttp.send("username=" + value);
        }
        
        
        function $(elementid) {
            return document.getElementById(elementid);
        }
        
    </script>
    
  </head>
 
  <body>
    <!--  baidu: <input type="text" name="text" οnkeyup="chkInput()" /><br /> -->
    请输入要查询的账号 : <input type="text" name="username" οnblur="chkInput(this.value)"/><br />
 账号信息:<br />
账号: <span id="username"></span>
 密码:<span id="password"></span>
 年龄:<span id="age"></span>
 性别:<span id="gender"></span>
  </body>
</html>

~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~  ~

d.测试

运行项目

打开浏览器,出现提示输入要查询的账号的文本输入框

输入指定的用户之后,从服务器返回具体的用户数据并打印到当前页面上

*  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *


附注:XMLHttpRequest的几种状态

属性

描述

onreadystatechange

每次状态改变所触发事件的事件处理程序

responseText

从服务器进程返回数据的字符串形式

responseXML

从服务器进程返回的DOM兼容的文档数据对象

status

从服务器返回的数字代码

常见:404(资源未查询到)200(资源正确接收)500(服务器错误)

status Text

伴随状态码的字符串信息

readyState

对象状态值

0—未初始化 1—正在加载  2—加载完毕 3—交互 4—完成



待续——JSON

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值