加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ajax

发布时间:2020-12-15 22:10:48 所属栏目:百科 来源:网络整理
导读:一、Ajax工作过程 1、JavaScript脚本使用XMLHttpRequest对象向服务器发送请求。发送请求时,既可以发送GET请求,也可以发送POST请求; 2、JavaScript脚本使用XMLHttpRequest对象解析服务器响应数据; 3、JavaScript脚本通过DOM动态更新HTML页面。也可以为服

一、Ajax工作过程

1、JavaScript脚本使用XMLHttpRequest对象向服务器发送请求。发送请求时,既可以发送GET请求,也可以发送POST请求;

2、JavaScript脚本使用XMLHttpRequest对象解析服务器响应数据;

3、JavaScript脚本通过DOM动态更新HTML页面。也可以为服务器响应数据增加CSS样式表,在当前页面的某个部分加以显示。

二、Ajax的核心XMLHttpRequest

functioncreateXMLHttpRequest() {

//对于基于Mozilla的浏览器

if(window.XMLHttpRequest) {

//对于基于Mozilla的浏览器,直接创建XMLHttpRequest对象

returnnew XMLHttpRequest();

} elseif(window.ActiveXObject) {

//IE浏览器中XMLHTTP的实现版本并不相同

var msxmls = ["MSXML3","MSXML2", "Microsoft"];

for(var i=0; i<msxmls.length; i++){

try {

//创建XMLHTTP组件

returnnew ActiveXObject(msxmls[i] + ".XMLHTTP");

} catch(e) {

alert("浏览器不支持XMLHTTP控件");

}

}

}

}

三、XMLHttpRequest的方法

open(“method”,“url”[,”asyncFlag[,”username”[,”password”]]])

建立与服务器url的链接,并设置请求的方法,以及是否使用异步请求。如果远程服务需要用户名、密码,则提供对应的用户名和密码;

setRequestHeader(“label”,”value”)

在发送请求之前,设置请求头;

send(content)

发送请求。content为请求参数;

abort()

停止发送当前请求;

getResponseHeader(“headerLabel”)

根据响应头的名字,获取对应的响应头;

getAllResponseHeader()

获取服务器返回的全部响应头。

四、XMLHttpRequest的属性

onreadystatechange

用于指定XMLHttpRequest对象状态改变时的事件处理函数;

readyState

XMLHttpRequest对象的处理状态;

status

服务器返回的状态码,只有当服务器的响应已经完成时,才会有该状态码;

statusText

服务器返回的状态文本信息,只有当服务器的响应已经完成时,才会有该状态文本信息;

responseText

获取服务器的响应文本;

responseXML

获取服务器响应的XML文档对象。

表4-1 XMLHttpRequest对象的处理状态(readyState)取值及含义

readyState取值

含义

0

XMLHttpRequest对象还没有完成初始化

1

XMLHttpRequest对象开始发送请求

2

XMLHttpRequest对象的请求发送完成

3

XMLHttpRequest对象开始读取服务器的响应

4

XMLHttpRequest对象读取服务器响应结束

表4-2 服务器返回的状态码(status)和状态文本信息(statusText)的含义

status

statusText

200

服务器响应正常

304

该资源在上次请求之后没有任何修改,由于浏览器的缓存机制

400

无法找到请求的资源

401

访问资源的权限不够

403

没有权限访问资源

404

需要访问的资源不存在

405

需要访问的资源被禁止

407

访问的资源需要代理身份验证

414

请求的url太长

500

服务器内部错误

五、Ajax聊天室代码

图5-1 目录结构

web.xml:

<?xml version=”1.0” encoding=”UTF-8”?>

<web-appversion=”2.5”

xmlns=”http://java.sun.com/xml/ns/javaee”

xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”

xsi:schemaLocation=”http://java.sun.com/xml/ns/javaee

http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd”>

<servlet>

<servlet-name>ChatServlet</servlet-name>

<servlet-class>chat.ChatServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>ChatServlet</servlet-name>

<url-pattern>/ChatServlet</url-pattern>

</servlet-mapping>

<welcome-file-list>

<welcome-file>index.jsp</welcome-file>

</welcome-file-list>

</web-app>

ChatRoom.jsp:

<%@ page language="java" import="java.util.*"pageEncoding="GB18030"%>

<!DOCTYPE HTMLPUBLIC "-//W3C//DTD HTML4.01 Transitional//EN">

<html>

<head>

<title>Ajax ChatRoom.</title>

<meta http-equiv="pragma"content="no-cache">

<metahttp-equiv="cache-control" content="no-cache">

<meta http-equiv="expires"content="0">

<metahttp-equiv="keywords"content="keyword1,keyword2,keyword3">

<meta http-equiv="description"content="Ajax ChatRoom.">

<style type="text/css">

html,body {

margin:0pxauto;

text-align:center;

}

#form1 {

text-align:center;

}

#apDiv1 {

width:800px;

height:450px;

text-align:center;

background-color: #00FFFF;

}

#commonalityContent {

width:600px;

readonly:true;

}

#inputContent {

width:500px;

height:23px;

}

#tijiao {

border:#999999 1pxsolid;

width:70px;

height:23px;

background:#00FF66;

cursor:pointer;

}

h1 {

font-family:"宋体";

font-size:24px;

font-style:normal;

font-variant:normal;

font-weight:700;

line-height: 30px;

}

</style>

</head>

<body>

<br>

<br>

<form name="form1"id="form1" method="post" onsubmit = "returnfalse;">

<div id="apDiv1">

<br>

<h1 align="center">似水流年-聊天室</h1>

<textareaname="commonalityContent" id="commonalityContent"cols="80" rows="20"readonly="readonly"></textarea>

<palign="center">

<input name="inputContent"type="text" id="inputContent" size="70"onKeyPress="enterHandler(event);">

&nbsp;&nbsp;

<input type="button"name="tijiao" id="tijiao" value="发送" onclick = "sendRequest()">

</p>

</div>

</form>

<script type="text/javascript">

functioncreateXMLHttpRequest() {

//对于基于Mozila的浏览器

if(window.XMLHttpRequest) {

//对于基于Mozilla的浏览器,直接创建XMLHttpRequest对象

XMLHttpReq = newXMLHttpRequest();

} elseif(window.ActiveXObject) {

//IE浏览器中XMLHTTP的实现版本并不相同

var msxmls =["MSXML3","MSXML2","Microsoft"];

for(var i=0;i<msxmls.length; i++){

try {

//创建XMLHTTP组件

XMLHttpReq= new ActiveXObject(msxmls[i] + ".XMLHTTP");

} catch(e){

alert("浏览器不支持XMLHTTP控件");

}

}

} else {

alert('error');

}

}

//发送请求函数

functionsendRequest() {

varchatMsg = trim(document.getElementById("inputContent").value);

createXMLHttpRequest();

varurl = "../ChatServlet";

XMLHttpReq.open("POST",url,true);

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

XMLHttpReq.onreadystatechange= processResponse;

document.getElementById("inputContent").value= "";

XMLHttpReq.send("chatMsg="+ chatMsg);

}

functionsendEmptyRequest() {

createXMLHttpRequest();

var url ="../ChatServlet";

XMLHttpReq.open("POST",true);

XMLHttpReq.setRequestHeader("Content-Type","application/x-www-for-urlencoded");

XMLHttpReq.onreadystatechange= processResponse;

XMLHttpReq.send(null);

setTimeout("sendEmptyRequest()",800);

}

//处理返回信息函数

functionprocessResponse() {

if(XMLHttpReq.readyState== 4) {

if(XMLHttpReq.status== 200) {

varcommonalityContent = document.getElementById("commonalityContent");

commonalityContent.value= XMLHttpReq.responseText;

commonalityContent.doScroll("scrollbarPageDown");

document.getElementById("inputContent").focus();

}else if(XMLHttpReq.status == 404) {

//alert('资源丢失...');

}else if(XMLHttpReq.status == 505) {

//alert('服务器内部错误...');

}

}else {

//alert("XMLHttpRequest对象异常...");

}

}

//键盘处理函数

functionenterHandler(event) {

varkeyCode = event.keyCode;

if(keyCode== 13) {

sendRequest();

}

}

sendEmptyRequest();

//去掉字符串两端空白字符

functiontrim(s) {

returns.replace(/^s*/,"").replace(/s*$/,"");

}

</script>

</body>

</html>

ChatServlet.java:

package chat;

importjava.io.IOException;

importjava.io.PrintWriter;

importjava.util.ArrayList;

import java.util.List;

importjavax.servlet.ServletContext;

importjavax.servlet.ServletException;

importjavax.servlet.http.HttpServlet;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

importjavax.servlet.http.HttpSession;

public classChatServlet extends HttpServlet {

public void doGet(HttpServletRequestrequest,HttpServletResponse response) throws ServletException,IOException {

doPost(request,response);

}

public void doPost(HttpServletRequestrequest,HttpServletResponse response)

throwsServletException,IOException {

request.setCharacterEncoding("UTF-8");

String msg =request.getParameter("chatMsg");

ServletContext context =this.getServletContext();

List chatContentList =(ArrayList)context.getAttribute("chatList");

//如果接收到的信息不为null或"",存储该次聊天内容,否则不进行处理

if(msg != null &&!"".equals(msg) && !"undefined".equals(msg)) {

if(chatContentList== null) {

chatContentList= new ArrayList();

chatContentList.add(msg);

} else {

int len =chatContentList.size();

if(len <100) {

chatContentList.add(msg);

} else {

chatContentList.remove(0);

chatContentList.add(msg);

}

}

context.setAttribute("chatList",chatContentList);

}

String s = "";

if(chatContentList!=null&& chatContentList.size()>0) {

int len =chatContentList.size();

for(int i=0;i<len; i++) {

if(i !=len-1) {

s+= chatContentList.get(i).toString() + "n";

} else {

s+= chatContentList.get(i).toString();

}

}

}

response.setContentType("text/html;charset=GBK");

PrintWriter out =response.getWriter();

out.write(s);

out.flush();

out.close();

}

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读