Ajax Request
js 代码
- var http_request = false;
- function makeRequest(url, queryStr, methodName) {
- http_request = false;
- if (window.XMLHttpRequest) { // Mozilla, Safari,...
- http_request = new XMLHttpRequest();
- if (http_request.overrideMimeType) {
- http_request.overrideMimeType('text/xml');
- }
- } else if (window.ActiveXObject) { // IE
- try {
- http_request = new ActiveXObject("Msxml2.XMLHTTP");
- } catch (e) {
- try {
- http_request = new ActiveXObject("Microsoft.XMLHTTP");
- } catch (e) {
- }
- }
- }
- if (!http_request) {
- alert('Giving up :( Cannot create an XMLHTTP instance');
- return false;
- }
- http_request.onreadystatechange = methodName;
- http_request.open('POST', url, true);
- http_request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
- http_request.send(queryStr);
- }
readyState的取值如下:
- 0 (未初始化)
- 1 (正在装载)
- 2 (装载完毕)
- 3 (交互中)
- 4 (完成)
http_request.responseText 取得 String
http_request.responseXML 取得 Xml
XMLHttpRequest 参考
Methods
Method Description abort() Cancels the current request getAllResponseHeaders() Returns the complete set of http headers as a string getResponseHeader("headername") Returns the value of the specified http header open("method","URL",async,"uname","pswd") Specifies the method, URL, and other optional attributes of a request
The method parameter can have a value of "GET", "POST", or "PUT" (use "GET" when requesting data and use "POST" when sending data (especially if the length of the data is greater than 512 bytes.
The URL parameter may be either a relative or complete URL.
The async parameter specifies whether the request should be handled asynchronously or not. true means that script processing carries on after the send() method, without waiting for a response. false means that the script waits for a response before continuing script processing
send(content) Sends the request setRequestHeader("label","value") Adds a label/value pair to the http header to be sent
Properties
Property Description onreadystatechange An event handler for an event that fires at every state change readyState Returns the state of the object:
0 = uninitialized
1 = loading
2 = loaded
3 = interactive
4 = complete
responseText Returns the response as a string responseXML Returns the response as XML. This property returns an XML document object, which can be examined and parsed using W3C DOM node tree methods and properties status Returns the status as a number (e.g. 404 for "Not Found" or 200 for "OK") statusText Returns the status as a string (e.g. "Not Found" or "OK")