您的位置:首页 > 理论基础 > 计算机网络

Ajax核心知识——XMLHttpRequest

2016-04-28 11:39 567 查看
第一节:XMLHttpRequest
对象创建

所有现代浏览器均支持
XMLHttpRequest
对象(IE5
和 IE6
使用 ActiveXObject) 。
XMLHttpRequest
用于在后台与服务器交换数据。这意味着可以在不重新加载整个网页的情况下,对网页的某
部分进行更新

第二节:XMLHttpRequest 对象请求后台

1、open(method,url,async)

规定请求的类型、URL
以及是否异步处理请求。

method:请求的类型;GET

POST
url:文件在服务器上的位置 (本文用servlet项目,放在web.xml配置中)
async:true(异步)或
false(同步)一般都true  异步处理

2、send(string)
将请求发送到服务器。
string:仅用于
POST
请求

注意,本文是servlet项目,先写java消息处理代码

package com.java1234.web;

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;

public class GetAjaxNameServlet extends HttpServlet{

/**
*
*/
private static final long serialVersionUID = 1L;

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

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");//返回编码
PrintWriter out=response.getWriter();

String name=request.getParameter("name");
String age=request.getParameter("age");
String type=request.getParameter("type");
System.out.println("name="+name);
System.out.println("age="+age);
System.out.println("type="+type);
out.println(type);
out.flush();
out.close();
}

}


然后配置servlet配置,在web.xml中 添加
<servlet>
<servlet-name>getAjaxNameServlet</servlet-name>
<servlet-class>com.java1234.web.GetAjaxNameServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>getAjaxNameServlet</servlet-name>
<url-pattern>/getAjaxName</url-pattern>
</servlet-mapping>

然后创建一个jsp项目,ajax.jsp

三种写法:

<script type="text/javascript">

// getAjaxName 对应web.xml的配置位置、传3个参数 type、name、age
//open get 方法
function loadNameByOpenGet(){
var xmlHttp;
//判断一下 出了IE5、6以下没有XMLHttpRequest,其他主流浏览器都支持
if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();
}else{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}

xmlHttp.open("get", "getAjaxName?type=open_get&name=jayson1&age=11", true);
xmlHttp.send();

}

//open post方法
function loadNameByOpenPost()
{
var xmlHttp;
//判断一下 出了IE5、6以下没有XMLHttpRequest,其他主流浏览器都支持
if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();
}else{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}

xmlHttp.open("post", "getAjaxName?type=open_post&name=jayson2&age=22", true);
xmlHttp.send();
}

//send post 方法
function loadNameBySend()
{

var xmlHttp;
//判断一下 出了IE5、6以下没有XMLHttpRequest,其他主流浏览器都支持
if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();
}else{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}

xmlHttp.open("post", "getAjaxName", true);//打开
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHttp.send("type=send&name=jayson3&age=33");
}

</script>

后面放3个按钮,调用三个方法
<body>
<center><h1>Ajax获取数据</h1></center>
<div style="text-align: center;">
<div><input type="button" onclick="loadNameByOpenGet()" value="open_get"/></div>
</div>
<br>
<div style="text-align: center;">
<div><input type="button" onclick="loadNameByOpenPost()" value="open_post"/></div>
</div>
<br>
<div style="text-align: center;">
<div><input type="button" onclick="loadNameBySend()" value="send_post"/></div>
</div>
<br>
</body>

添加项目到tomcat,启动项目

服务器开
4000
启后,输入测试地址:http://localhost:8080/HeadFirstAjaxJsonChap02/ajax.jsp    得到运行效果

从上到下分别点击按钮,输入效果如下

说明java那边的代码 GetAjaxNameServlet.java 收到消息了

解释一下:

GET
还是 POST?

POST 相比,GET
更简单也更快,并且在大部分情况下都能用。
然而,在以下情况中,请使用
POST 请求:
无法使用缓存文件(更新服务器上的文件或数据库)
向服务器发送大量数据(POST
没有数据量限制)
发送包含未知字符的用户输入时,POST

GET 更稳定也更可靠
setRequestHeader(header,value)
向请求添加
HTTP 头。
header:
规定头的名称
value:
规定头的值
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
异步
- True 或
False?
AJAX
指的是异步 JavaScript
和 XML(Asynchronous JavaScript and XML)


True 的话,表示的是异步,异步表示程序请求服务器的同时,程序可以继续执行;能提高系统的运行效率;

False 的话,表示同步,JavaScript
会等到服务器响应就绪才继续执行。如果服务器繁忙或缓慢,应用程序会
挂起或停止。
我们一般都是用
True;

第三节:XMLHttpRequest
对象响应服务器

我们使用 刚才的第三种发送方法,send—post 方法做测试,

新增代码,ajax.jsp 完整代码如下

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">

// getAjaxName 对应web.xml的配置位置、传3个参数 type、name、age
//open get 方法
function loadNameByOpenGet(){
var xmlHttp;
//判断一下 出了IE5、6以下没有XMLHttpRequest,其他主流浏览器都支持
if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();
}else{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}

xmlHttp.open("get", "getAjaxName?type=open_get&name=jayson1&age=11", true);
xmlHttp.send();

}

//open post方法
function loadNameByOpenPost()
{
var xmlHttp;
//判断一下 出了IE5、6以下没有XMLHttpRequest,其他主流浏览器都支持
if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();
}else{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}

xmlHttp.open("post", "getAjaxName?type=open_post&name=jayson2&age=22", true);
xmlHttp.send();
}

//send post 方法
function loadNameBySend()
{

var xmlHttp;
//判断一下 出了IE5、6以下没有XMLHttpRequest,其他主流浏览器都支持
if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();
}else{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}

xmlHttp.open("post", "getAjaxName", true);//打开
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHttp.send("type=send&name=jayson3&age=33");
}

//响应服务器 代码测试
function loadNameByState()
{

var xmlHttp;
if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();
}else{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
alert("readState状态:"+xmlHttp.readyState+";status状态:"+xmlHttp.status);
xmlHttp.onreadystatechange=function(){
alert("function_readState状态:"+xmlHttp.readyState+";status状态:"+xmlHttp.status);
if(xmlHttp.readyState==4 && xmlHttp.status==200){
alert("returnNum:"+xmlHttp.responseText);
document.getElementById("name2").value=xmlHttp.responseText;
}
};

xmlHttp.open("post", "getAjaxName", true);//打开
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHttp.send("type=checkstate&name=jayson4&age=44");
}

</script>
</head>
<body>
<center><h1>Ajax获取数据</h1></center>
<div style="text-align: center;">
<div><input type="button" onclick="loadNameByOpenGet()" value="open_get"/></div>
</div>
<br>
<div style="text-align: center;">
<div><input type="button" onclick="loadNameByOpenPost()" value="open_post"/></div>
</div>
<br>
<div style="text-align: center;">
<div><input type="button" onclick="loadNameBySend()" value="send_post"/></div>
</div>
<br>
<div style="text-align: center;">
<div><input type="button" onclick="loadNameByState()" value="checkState"/>  <input type="text" id="name_state" name="name_state" /></div>
</div>
</body>
</html>

刚才的服务器已经开启的情况下,我们只需刷新一下 测试地址:http://localhost:8080/HeadFirstAjaxJsonChap02/ajax.jsp
运行效果 你会发现 整个过程中 ,执行5次步骤 ,readState会从0-4、且当道2后面,status一直保持为200,说明接收成功了!



当readyState==4且status==200时,客户端返回服务器发送的数据,在responseText里面,所以又弹了一次面板



解释一下:

onreadystatechange
事件
当请求被发送到服务器时,我们需要执行一些基于响应的任务。
每当
readyState 改变时,就会触发
onreadystatechange 事件。
readyState
属性存有 XMLHttpRequest
的状态信息。
下面是
XMLHttpRequest 对象的三个重要的属性:
onreadystatechange存储函数(或函数名) ,每当
readyState
属性改变时,就会调用该函数。
readyState
存有
XMLHttpRequest 的状态。从
0 到
4 发生变化。
0:
请求未初始化
1:
服务器连接已建立
2:
请求已接收
3:
请求处理中
4:
请求已完成,且响应已就绪
status
200: "OK"
404:
未找到页面

onreadystatechange 事件中,我们规定当服务器响应已做好被处理的准备时所执行的任务。
如需获得来自服务器的响应,请使用
XMLHttpRequest 对象的
responseText 或
responseXML 属性。
属性 描述
responseText
获得字符串形式的响应数据。
responseXML
获得 XML
形式的响应数据。 (了解即可)



本次由java1234网站的ajax项目中总结
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  servlet ajax