Chinaunix首页 | 论坛 | 博客
  • 博客访问: 6209566
  • 博文数量: 2759
  • 博客积分: 1021
  • 博客等级: 中士
  • 技术积分: 4091
  • 用 户 组: 普通用户
  • 注册时间: 2012-03-11 14:14
文章分类

全部博文(2759)

文章存档

2019年(1)

2017年(84)

2016年(196)

2015年(204)

2014年(636)

2013年(1176)

2012年(463)

分类:

2012-05-16 10:09:09

原文地址:AJAX 作者:yourtommy

AJAX = Asynchronous JavaScript and XML。它不是新的语言,而是使用现有标准的新的方式。它可以和服务器交换数据,更新网页的一部分,而不重新装载整个网页。

AJAX基于Internet标准,与平台或浏览器无关。它由以下部分组成:

  • XMLHttpRequest object (与服务器异步地交换数据)
  • JavaScript/DOM (与信息交互或显示信息)
  • CSS (定制数据的样式)
  • XML (传输数据的格式)
AJAX的工作流程是:

1、当浏览器的某个事件发生时,创建一个XHMHttpRequest对象,然后发送一个HttpRequest给服务器;

2、服务器处理HttpRequest,创建响应并返回数据给浏览器;

3、浏览器用javascript处理返回的数据,并更新网页内容。


AJAX的关键对象是XMLHttpRequest Object,所有当代浏览器都有内置这个对象。

它使用open和send方法向服务器发送请求。

MethodDescription
open(method,url,async)Specifies the type of request, the URL, and if the request should be handled asynchronously or not.

method: the type of request: GET or POST
url: the location of the file on the server
async: true (asynchronous) or false (synchronous)
send(string)Sends the request off to the server.

string: Only used for POST requests

例如:



除了GET方法,我们也可以使用POST方法。如果要传入参数,我们需要使用setRequestHeader()方法:

MethodDescription
setRequestHeader(header,value)Adds HTTP headers to the request.

header: specifies the header name
value: specifies the header value

同时在send方法里指定要传输的数据。

例如:



XMLHttpRequest对象的responseText和respon***ML属性都可以得到服务器的响应。

PropertyDescription
responseTextget the response data as a string
respon***MLget the response data as XML data

前面已经演示过responseText,下面是respon***ML的例子:



关于处理服务器响应的属性有:

PropertyDescription
onreadystatechangeStores a function (or the name of a function) to be called automatically each time the readyState property changes
readyStateHolds the status of the XMLHttpRequest. Changes from 0 to 4: 
0: request not initialized 
1: server connection established
2: request received 
3: processing request 
4: request finished and response is ready
status200: "OK"
404: Page not found

阅读(664) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~