分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 技术分享

Ajax的使用

发布时间:2023-09-06 01:21责任编辑:彭小芳关键词:Ajax

、AJAX简介(本文的例子都使用的是原生的ajax)
  老技术新用法
、异步和同步区别
、XMLHttpRequest对象(面试题)
属性:
  readyState:  

    0:未初始化

    1:open方法已经调用了

    2:send方法已经调用了

    3:接收到了响应消息头,但没有接收到正文

    4:接收到了响应正文。响应结束

  responseText:只读的。返回的是String

    作用:接收服务器返回的文本类型的正文数据。

  responseXML:只读的。返回的是Document对象(JS中文档模型)

    作用:接收服务器返回的XML类型的正文数据。

  status:只读的。返回的是short

    作用:接收服务器返回的响应状态码

  statusText:只读的。返回的是String

    作用:接收服务器返回的响应吗描述

方法:

l open(String method,String url,boolean async):建立与服务器的链接。

  method:请求方式。GET|POST

  url:请求的服务器地址。

  async:是否是异步。true是异步的。默认就是true。

l send(String data):发出请求。data参数是请求正文的内容数据。

l setRequestHeader(String headerName,String headerValue):设置请求消息头。

l getAllResponseHeaders():返回所有的响应消息头。是一个String字符串。

l getResponseHeader(headerName):返回指定头的值。是一个String字符串。

事件处理器:onreadystatechange:执向一个函数。XMLHttpRequest对象的readyState的每次变化都会触发onreadystatechange指向的事件处理器。

、GET和POST请求的发送
、服务器端返回的数据类型:
  XML: 返回的是xml对象
  JSON:返回的是文本类型,需要转换

编码步骤:

 1 function getXHR() { 2 ????var xmlHttp; 3 ?4 ????try { 5 ????????// Firefox, Opera 8.0+, Safari 6 ????????xmlHttp = new XMLHttpRequest(); 7 ????} catch (e) { 8 ?9 ????????// Internet Explorer10 ????????try {11 ????????????xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");12 ????????} catch (e) {13 14 ????????????try {15 ????????????????xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");16 ????????????} catch (e) {17 ????????????????alert("您的浏览器不支持AJAX!");18 ????????????????return false;19 ????????????}20 ????????}21 ????}22 ????return xmlHttp;23 }
util.js
 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 ?3 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 4 <html> 5 ??<head> 6 ????<title>AJAX的编码步骤:测试异步交互是可行的</title> 7 ?????8 ????<meta http-equiv="pragma" content="no-cache"> 9 ????<meta http-equiv="cache-control" content="no-cache">10 ????<meta http-equiv="expires" content="0">11 ????<!--12 ????<link rel="stylesheet" type="text/css" href="styles.css">13 ????-->14 ????<script type="text/javascript" src="${pageContext.request.contextPath}/util.js"></script>15 ????<script type="text/javascript">16 ????????window.onload=function(){17 ????????????//window.onload是一个事件,当文档加载完成之后触发该事件18 ????????????document.getElementById("bt1").onclick=function(){19 ????????????????//发出异步请求:步骤20 ????????????????21 ????????????????//1、得到xhr(XMLHttpRequest)对象22 ????????????????var xhr = getXHR();23 ????????????????//2、注册状态变化监听器24 ????????????????xhr.onreadystatechange=function(){25 ????????????????????//做出具体的处理26 ????????????????????if(xhr.readyState==4){//接收到了响应正文。响应结束27 ????????????????????????if(xhr.status==200){//200:服务器成功返回页面28 ????????????????????????????alert("服务器已经响应结束了,去看看吧");29 ????????????????????????}30 ????????????????????}31 ????????????????}32 ????????????????//3、建立与服务器的链接33 ????????????????//如果访问的地址相同,浏览器就不会真正的发出请求 ??????time="+new Date().getTime()34 ????????????????xhr.open("GET","${pageContext.request.contextPath}/servlet/ServletDemo1?time=");35 ????????????????//4、向服务器发出请求36 ????????????????xhr.send(null);//没有正文37 ????????????}38 ????????}39 ????</script>40 ??</head>41 ??42 ??<body>43 ????<input id="bt1" type="button" value="点我呀"/>44 ????<%--45 ????????不论type是什么类型,只要单击鼠标就会执行,window.load=function事件46 ??????--%>47 ??</body>48 </html>
View Code

一个验证用户名是否存在例子:(理解POST和GET提交时send方法传值的区别)

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 ?3 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 4 <html> 5 ??<head> 6 ????<title>检测用户名是否可用</title> 7 ?????8 ????<meta http-equiv="pragma" content="no-cache"> 9 ????<meta http-equiv="cache-control" content="no-cache">10 ????<meta http-equiv="expires" content="0">11 ????<script type="text/javascript" src="${pageContext.request.contextPath}/util.js"></script>12 ????<!--13 ????<link rel="stylesheet" type="text/css" href="styles.css">14 ????-->15 ????<script type="text/javascript">16 ????????window.onload=function(){17 ????????????document.getElementById("username").onblur=function(){//失去焦点18 ????????????????if(this.value==""){19 ????????????????????alert("请输入用户名");20 ????????????????????this.focus();//恢复焦点21 ????????????????????return;22 ????????????????}23 ????????????????//发出异步请求24 ????????????????var xhr = getXHR();25 ????????????????xhr.onreadystatechange=function(){26 ????????????????????if(xhr.readyState==4){27 ????????????????????????if(xhr.status==200){28 ????????????????????????????29 ????????????????????????????document.getElementById("msg").innerHTML=xhr.responseText;30 ????????????????????????????//responseText接收服务器返回的文本类型的正文数据。31 ????????????????????????????//放到名为msg的span(属于一个行内元素)中32 ????????????????????????}33 ????????????????????}34 ????????????????}35 ????????????????/*GET提交时,在send中传值是不起作用的;36 ????????????????xhr.open("GET","${pageContext.request.contextPath}/servlet/ServletDemo2?username="+this.value+"&time="+new Date().getTime());37 ????????????????xhr.send(null);38 ????????????????*/39 ????????????????40 ????????????????//41 ????????????????xhr.open("POST","${pageContext.request.contextPath}/servlet/ServletDemo2?time="+new Date().getTime());42 ????????????????//设置请求消息头:告知客户端提交的正文的MIME类型43 ????????????????xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");44 ????????????????xhr.send("username="+this.value);45 ????????????}46 ????????}47 ????</script>48 ??</head>49 ??50 ??<body>51 ????<form action="" method="post">52 ????????用户名:<input type="text" id="username" name="username"/><span id="msg"></span><br/>53 ????????密码:<input type="password" id="password" name="password"/><br/>54 ????????<input type="submit" value="注册"/>55 ????</form>56 ??</body>57 </html>
页面
 1 package com.itheima.servlet; 2 ?3 import java.io.IOException; 4 ?5 import javax.servlet.ServletException; 6 import javax.servlet.http.HttpServlet; 7 import javax.servlet.http.HttpServletRequest; 8 import javax.servlet.http.HttpServletResponse; 9 10 public class ServletDemo2 extends HttpServlet {11 ????private String usernames[] = {"admin","wzhting"};//预先存在的用户名,也可连接数据库取;此处只是为了说明ajax做了简化处理12 13 ????public void doGet(HttpServletRequest request, HttpServletResponse response)14 ????????????throws ServletException, IOException {15 ????????String username = request.getParameter("username");16 ????????boolean b = false;//是否可用17 ????????for(String s:usernames){18 ????????????if(s.equals(username)){19 ????????????????b = true;20 ????????????????break;21 ????????????}22 ????????}23 ????????24 ????????response.setContentType("text/html;charset=UTF-8");25 ????????if(b){26 ????????????response.getWriter().write("<font color=‘red‘>用户名不可用</font>");27 ????????}else{28 ????????????response.getWriter().write("<font color=‘green‘>用户可用</font>");29 ????????}30 ????????31 ????}32 33 ????public void doPost(HttpServletRequest request, HttpServletResponse response)34 ????????????throws ServletException, IOException {35 ????????doGet(request, response);36 ????}37 38 }
ServletDemo2

一个理解(利用jsp页面返回数据)例子:

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 ?3 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 4 <html> 5 ??<head> 6 ????<title>显示所有的商品</title> 7 ?????8 ????<meta http-equiv="pragma" content="no-cache"> 9 ????<meta http-equiv="cache-control" content="no-cache">10 ????<meta http-equiv="expires" content="0">11 ????<script type="text/javascript" src="${pageContext.request.contextPath}/util.js"></script>12 ????<!--13 ????<link rel="stylesheet" type="text/css" href="styles.css">14 ????-->15 ????<style type="text/css">16 ????????.odd{17 ????????????background-color: #c3f3c3;18 ????????}19 ????????.even{20 ????????????background-color: #f3c3f3;21 ????????}22 ????</style>23 ????<script type="text/javascript">24 ????????var flag = false;25 ????????window.onload=function(){26 ????????????document.getElementById("bt1").onclick=function(){27 ????????????????//发出异步请求28 ????????????????var xhr = getXHR();29 ????????????????xhr.onreadystatechange=function(){30 ????????????????????if(xhr.readyState==4){31 ????????????????????????if(xhr.status==200){32 ????????????????????????????if (flag == false) {33 ????????????????????????????????document.getElementById("d1").innerHTML=xhr.responseText;// ?文本类型 text/*34 ????????????????????????????????flag = true;35 ????????????????????????????} else {36 ????????????????????????????????document.getElementById("d1").innerHTML="";37 ????????????????????????????????flag = false;38 ????????????????????????????}39 ????????????????????????}40 ????????????????????}41 ????????????????}42 ????????????????xhr.open("GET","${pageContext.request.contextPath}/servlet/ServletDemo3?time="+new Date().getTime());43 ????????????????xhr.send(null);44 ????????????}45 ????????}46 ????</script>47 ??</head>48 ??49 ??<body>50 ????<input type="button" id="bt1" value="显示商品"/>51 ????<hr/>52 ????<div id="d1"></div>53 ??</body>54 </html>
主页面
 1 package com.itheima.servlet; 2 ?3 import java.io.IOException; 4 import java.util.ArrayList; 5 import java.util.List; 6 ?7 import javax.servlet.ServletException; 8 import javax.servlet.http.HttpServlet; 9 import javax.servlet.http.HttpServletRequest;10 import javax.servlet.http.HttpServletResponse;11 12 import com.itheima.domain.Product;13 14 public class ServletDemo3 extends HttpServlet {15 ????private List<Product> products = new ArrayList<Product>();16 ????public void init() throws ServletException {17 ????????products.add(new Product(1, "充气筒", 20));18 ????????products.add(new Product(2, "三国杀", 10));19 ????????products.add(new Product(3, "扑克", 10));20 ????????products.add(new Product(4, "洗衣粉", 10));21 ????????products.add(new Product(5, "肥皂", 7));22 ????}23 24 ????public void doGet(HttpServletRequest request, HttpServletResponse response)25 ????????????throws ServletException, IOException {26 ????????request.setAttribute("products", products);27 ????????request.getRequestDispatcher("/listProducts.jsp").forward(request, response);28 ????????//jsp页面因为是先编译成servlet在运行的,而servlet中的jsp页面就变成了如下形式的代码29 ????????//out.write("<html>\r\n");30 ????????//所以response的是整个jsp页面31 ????}32 33 ????public void doPost(HttpServletRequest request, HttpServletResponse response)34 ????????????throws ServletException, IOException {35 ????????doGet(request, response);36 ????}37 38 }
ServletDemo3
 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 3 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 4 <html> 5 ??<head> 6 ????<title>title</title> 7 ?????8 ????<meta http-equiv="pragma" content="no-cache"> 9 ????<meta http-equiv="cache-control" content="no-cache">10 ????<meta http-equiv="expires" content="0">11 ????<!--12 ????<link rel="stylesheet" type="text/css" href="styles.css">13 ????-->14 ????15 ??</head>16 ??17 ??<body>18 ????<table border="1" width="438">19 ????????<tr>20 ????????????<th>编号</th><%-- th比表示标题的一格,会自动加黑加粗 --%>21 ????????????<th>名称</th>22 ????????????<th>单价</th>23 ????????</tr>24 ????????<c:forEach items="${products}" var="p" varStatus="vs">25 ????????????<tr class="${vs.index%2==0?‘odd‘:‘even‘ }">26 ????????????????<td>${p.id}</td>27 ????????????????<td>${p.name}</td>28 ????????????????<td>${p.price}</td>29 ????????????</tr>30 ????????</c:forEach>31 ????</table>32 ??</body>33 </html>
返回数据的jsp页面

结果表明:jsp页面因为是先编译成servlet再运行的,故jsp页面会变成了如下形式的代码:

  ??out.write("<html>\r\n"); ????out.write("\t<head>\r\n"); ????out.write("\t\t<title>title</title>\r\n"); ????out.write("\t</head>\r\n"); ????out.write("\t<bodystyle=\"background-color:lightblue\">\r\n"); ????out.write("\r\n");
   ?……

//所以jsp页面可以返还给xhr.responseText;即使servlet中没有response.getWriter().write("……");

 
 
 
 
 
 
 
 
 

Ajax的使用

原文地址:http://www.cnblogs.com/mmzs/p/7755728.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved