XMLHttpRequest对象

概述:

利用XMLHttpRequest对象,你可以在不用重新加载页面的情况下更新部分页面。

XMLHttpRequest对象用于在后台与服务器交换数据,它是开发者梦寐以求的对象,因为:

  1. 不用重新加载页面的情况下,就可以更新部分页面。

  2. 在页面完全加载的后,还可以与从服务器端请求数据。

  3. 在页面完全加载的后,还可以与从服务器端接受数据。

  4. 可以在后台想服务器发生数据。


创建XMLHttpRequest对象

所有当前主流浏览器(IE7+,Firefox, Chrome, Safari, andOpera),都有一个内建的XMLHttpRequest对象,创建语法是:xmlhttp=newXMLHttpRequest();
老版本的IE(IE5IE6)是使用ActiveX对象创建,创建语法:xmlhttp=newActiveXObject("Microsoft.XMLHTTP");

代码实例如下:

if(window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome,Opera, Safari
  xmlhttp=new XMLHttpRequest();
 }
else
  {// code for IE6, IE5
  xmlhttp=newActiveXObject("Microsoft.XMLHTTP");
  }


向服务器发送一个请求

为了向服务器端发送一个请求,我们用open()函数和send()函数:

xmlhttp.open("GET","xmlhttp_info.txt",true);
xmlhttp.send();

Method

Description

open(method,url,async)

Specifies the type of request, theURL, and if the request should be handled asynchronously ornot.

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 theserver.

string: Only used for POST requests

GETPOST

GET是比POST更简单更快,大部分情况下都是用GET,然而使用POST是在如下情况下:

  • cache文件不能用了。

  • 发送大量的数据给服务器。

  • 发送用户输入的内容,POSTGET方法更可靠更安全。


Url-服务器端的文件

open函数中的url参数是定位服务器上文件的。
xmlhttp.open("GET","xmlhttp_info.txt",true);


异步-Trueor False

想要异步发送数据,就要将open函数的asyn参数指定为true。对于web开发者来说,能够发送异步请求是一个很大的提高,大部分针对服务器的操作是非常耗时的;

通过发送异步请求,javascript不是一直等待服务器响应,而是:

  • 在等服务器响应时,执行其他脚本。

  • 当服务器响应之后,处理其响应。

Asyn=True时,需要在onreadystatechang事件上指定服务器响应之后的执行函数,如下:

xmlhttp.onreadystatechange=function()
 {
  if (xmlhttp.readyState==4 &&xmlhttp.status==200)
    {
   document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
   }
 }
xmlhttp.open("GET","xmlhttp_info.txt",true);
xmlhttp.send();

Asyn=False时,就不需要指定任何函数了。不过一般不推荐使用false,除非只是发送一些比较小数据量的请求。


服务器响应(ServerResponse)

获取服务器的响应,利用XMLHttpRequestresponseTextresponseXML属性即可。

Property

Description

responseText

get the response data as a string

responseXML

get the response data as XML data


Onreadystatechange事件

当一个向服务器的请求发送过去的时候,我们想执行一些基于响应的操作,onreadystatechange事件在每次readystate改变的时候被激活,readyState属性记录了XMLHttpRequest的状态,三个重要的XMLHttpRequest属性值如下:

Property

Description

onreadystatechange

Stores a function (or the name of afunction) to be called automatically each time the readyStateproperty changes

readyState

Holds the status of theXMLHttpRequest. Changes from 0 to 4:
0: request notinitialized
1: server connection established
2: requestreceived
3: processing request
4: request finished andresponse is ready

status

200: "OK"
404: Page notfound


原文:http://www.w3schools.com/dom/dom_httprequest.asp


原文地址:https://www.cnblogs.com/java20130722/p/3207139.html