Latest web development tutorials

XML DOM - HttpRequest objects

Through XMLHttpRequest object, you can update a section of a web page without reloading the entire page.


XMLHttpRequest Object

XMLHttpRequest object is used to exchange data with the server behind the scenes.

XMLHttpRequest object is adeveloper's dream, because you can:

  • Update web page without reloading the page
  • After the page is loaded from the server request data
  • After the page has loaded data received from the server
  • Sending data to the server in the background

Create XMLHttpRequest object

All modern browsers (IE7 +, Firefox, Chrome, Safari and Opera) has a built-in XMLHttpRequest object.

Create XMLHttpRequest object syntax

xmlhttp=new XMLHttpRequest();

Older versions of Internet Explorer (IE5 and IE6) using ActiveX objects:

xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

To handle all modern browsers, including IE5 and IE6, please check whether the browser supports the XMLHttpRequest object. If so, then create an XMLHttpRequest object, if it does not, create an ActiveX object:

Examples

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

try it"


Send a request to the server

In order to send a request to the server, we use the XMLHttpRequest object's open () and send () method:

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

方法 描述
open(method,url,async) 规定请求的类型,URL,请求是否应该进行异步处理。

method:请求的类型:GET 或 POST
url:文件在服务器上的位置
async:true(异步)或 false(同步)
send(string) 发送请求到服务器。

string:仅用于 POST 请求


GET or POST?

GET simpler than POST and fast and can be used in most cases.

However, always use POST request under the following circumstances:

  • Cached files is not an option (or database file on the update server)
  • The amount of data sent to the server (POST no size limit) large
  • Sending user input (can contain unknown characters), POST stronger and more secure than GET

URL - file on the server

url argument open () method, is the address of a file on the server:

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

The file can be any type of file (such as .txt and .xml), or server script files (such as .html and .php, can perform actions on the server before sending back the response).


Asynchronous - True or False?

For asynchronous transmission request, async argument open () method must be set to true:

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

Send an asynchronous request for a Web developer is a huge step forward. On the server to perform many of the tasks are very time-consuming.

Through sent asynchronously, JavaScript does not need to wait for the server's response, but can be replaced by:

  • While waiting for response from the server, to execute additional scripts
  • Ready to handle the response when the response

Async = true

When using async = true, when in response to a predetermined function onreadystatechange event ready to be executed:

Examples

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();

try it"


Async = false

For the third parameter async = false, change the open () method is false:

xmlhttp.open("GET","xmlhttp_info.txt",false);

Not recommended async = false, but if handled several small request or can.

Remember, JavaScript in the server response does not continue until you are ready. If the server is busy or slow, the application will be suspended or stopped.

Note: When you use the async = false, do not write onreadystatechange function - just need to place the code after the send () statements to:

Examples

xmlhttp.open("GET","xmlhttp_info.txt",false);
xmlhttp.send();
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

try it"


Server Response

To get a response from the server, use the XMLHttpRequest object's responseText or responseXML property.

属性 描述
responseText 获取响应数据作为字符串
responseXML 获取响应数据作为 XML 数据


responseText property

If the response from the server is not XML, please use the responseText property.

responseText property returns the response as a string, you can use it accordingly:

Examples

document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

try it"


responseXML property

If the response is not XML from the server, and you want to resolve it to an XML object, use responseXML properties:

Examples

Request file cd_catalog.xml and parse the response:

xmlDoc=xmlhttp.responseXML;
var txt="";
x=xmlDoc.getElementsByTagName("ARTIST");
for (i=0;i<x.length;i++)
{
txt=txt + x[i].childNodes[0].nodeValue + "
";
}
document.getElementById("myDiv").innerHTML=txt;

try it"


onreadystatechange event

When the request is sent to the server, we need to perform some action based on the response.

onreadystatechange event is triggered each time the readyState changes.

XMLHttpRequest readyState property holds the status.

Three important properties of the XMLHttpRequest object:

属性 描述
onreadystatechange 存储函数(或函数的名称)在每次 readyState 属性变化时被自动调用
readyState 存放了 XMLHttpRequest 的状态。从 0 到 4 变化:
0:请求未初始化
1:服务器建立连接
2:收到的请求
3:处理请求
4:请求完成和响应准备就绪
status 200:"OK"
404:找不到页面

In the onreadystatechange event, we specify what will happen when the time is ready to process server response.

When the readyState is 4 or 200 state, the response prepared:

Examples

xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}

try it"

Note: onreadystatechange event is triggered each time the readyState changes, triggered a total of four times.


Examples s

More examples

By getAllResponseHeaders () to retrieve header information
To retrieve the resource (document) header information.

() Retrieves the specified header information getResponseHeader
To retrieve the resource (file) to specify the header information.

Content retrieval ASP file
When users type characters in the input field, how Web pages communicate with the Web server.

Retrieve content from the database
Web page how to extract information from the database through the XMLHttpRequest object.

Content retrieval XML file
Create an XMLHttpRequest to retrieve data from the XML file and display the data in an HTML table.