AJAX

1840阅读 0评论2012-05-14 yourtommy
分类:系统运维

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

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

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

上一篇:TCP/IP Protocols (8) -- Traceroute Program
下一篇:jQuery