---
title: "Ajax基础"
author: "wangdun119"
date: "2012-03-02T09:52:01Z"
tags: []
categories: ["Web前端"]
slug: "ajax"
draft: false
lastmod: "2012-03-02T09:52:01Z"
id: 1435189
url: "https://wangdun119.iteye.com/blog/1435189"
---

\[code="js"]var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }\[/code] open(method,url,async)； send(string)； Method Description 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 or POST? GET is simpler and faster than POST, and can be used in most cases. However, always use POST requests when: \[b]A cached file is not an option (update a file or database on the server)\[/b] \[b]Sending a large amount of data to the server (POST has no size limitations)\[/b] \[b]Sending user input (which can contain unknown characters), POST is more robust and secure than GET\[/b] Method Description setRequestHeader(header,value) Adds HTTP headers to the request. header: specifies the header name value: specifies the header value \[code="js"]xmlhttp.open("POST","ajax\_test.asp",true); xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xmlhttp.send("fname=Henry&lname=Ford");\[/code] Server Response To get the response from a server, use the responseText or responseXML property of the XMLHttpRequest object. Property Description responseText get the response data as a string responseXML get the response data as XML data \[b]The responseText Property\[/b] If the response from the server is not XML, use the responseText property. The responseText property returns the response as a string, and you can use it accordingly: \[code="js"] document.getElementById("myDiv").innerHTML=xmlhttp.responseText;\[/code] \[b]The responseXML Property\[/b] \[code="js"] xmlDoc=xmlhttp.responseXML; txt=""; x=xmlDoc.getElementsByTagName("ARTIST"); for (i=0;i"; } document.getElementById("myDiv").innerHTML=txt;\[/code] \[b] The onreadystatechange event\[/b] \[b]onreadystatechange\[/b] Stores a function (or the name of a function) to be called automatically each time the readyState property changes \[b]readyState\[/b] Holds 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 \[b]status \[/b] 200: "OK" 404: Page not found \[code="js"] xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } }\[/code]