Before reading this article, specify a common variable xhr and xhr code ajax object. Test Browser: ie is ie6, firefox is 2, and others are not tested. Ie6 is Internet Explorer and firefox2 is ff.
The most classic problem is the cache problem in ie.
If get is used, a cache problem occurs in ie. The code is executed only once. The solution is to add a timestamp or a random number to make the url unique, so that the cache issue under ie will not occur, or change to post for submission.
xhr.open("get","xxxx.aspx?_dc="+new Date().getTime(),true);
Case sensitivity of ajax Object Attributes
The w3c browser, such as ff, is case sensitive. For example, if (xhr. readystate = 4) is true in ie, but it does not work in ff because ie is case insensitive and ff is case sensitive. The standard format is if (xhr. readyState = 4), and there are also attributes responseText and responseXML.
Ajax status 0 problems
In some cases, xhr. status = 200 is added to test the ajax code and the code of xhr. status = 200 is not executed, so pay attention to this. Xhr. status = 200 is to be browsed through the server, and the server page does not have an error or returns the 200 status only when it is switched, this status is consistent with the status defined by the server when you access the page through a browser.
Drag the browser directly to view the result or double-click the html page to run it. If no error occurs, xhr. status is 0, not 200.
Therefore, you can add an xhr. status = 0. As follows:
if(xhr.status==200||xhr.status==0){ alert('ok');}
Another problem occurs when you drag the browser to view the result or double-click the html page. If you are requesting an xml file, you must use the responseXML attribute to return the xmlDom, however, the xmlDom attribute cannot be returned in ie. The solution is as follows.
ResponseXML
To use the responseXML attribute, the request is an xml file or a dynamic page with the response header set to "text/xml. Note that if a dynamic page is requested, do not forget to set contenttype to "text/xml "!!!!!!!! Remember ~~~~~~
Asp is response. contenttype = "text/html" asp.net is Response. ContentType = "text/html"; php is header ("content-type: text/xml ;");
If there is a problem in ie, when you drag it directly into the browser or double-click to run the html preview effect, even if the requested xml file, the xmldom cannot be returned using responseXML. You will know after testing, as shown below:
Showbo. xml
<?xml version="1.0" encoding="utf-8"?><showbo> <item>1</item> <item>2</item> <item>3</item> <item>4</item></showbo>
Test.html
Function getajax () {if (window. XMLHttpRequest) return new XMLHttpRequest (); else if (window. activeXObject) return new ActiveXObject ("microsoft. xmlhttp ");} var xhr = getajax (); xhr. onreadystatechange = function () {if (xhr. readyState = 4) {if (xhr. status = 200 | xhr. status = 0) {var doc = xhr. responseXML, item = doc. getElementsByTagName ("item"); alert (item. length); // The ie output is 0, and the ff output is 4. The xml tree structure does not appear to be generated in ie. The specific reason is ms .. } Else alert ('error \ n \ n' + xhr. status) ;}} xhr. open ("get", "showbo. xml? _ Dc = "+ new Date (). getTime (), true); xhr. send (null );
The solution is to use the microsoft. xmldom object to recreate the xml tree structure, as shown below:
Xhr. onreadystatechange = function () {if (xhr. readyState = 4) {if (xhr. status = 200 | xhr. status = 0) {var doc = xhr. responseXML; if (document. all & xhr. status = 0) {// rewrite the xml tree structure when ie is directly inserted into the browser. doc = new ActiveXObject ("microsoft. xmldom "); doc. loadXML (xhr. responseText); doc=doc.doc umentElement;} var item = doc. getElementsByTagName ("item"); alert (item. length); //} else alert ('error \ n \ n' + xhr. status );}}
Note the following when submitting a post request:
When submitting a post request, you must set content-type to "application/x-www-form-urlencoded" so that you can use request/request on a dynamic page. form/request. the querystring object obtains the value through the key. Otherwise, the binary data must be used. Then, you can analyze the binary data to generate a String object and obtain the corresponding value using the regular expression.
The xhr. setRequestHeader method must be used after open. Otherwise, an error occurs.
Xhr. open ("post", "xxxx. aspx ", true); xhr. setRequestHeader ("content-type", "application/x-www-form-urlencoded"); // here ....
Cross-origin problems
If the requested page is not of the current site, it will be cross-origin. The best solution is the xhr request on the server.
Recently, google's api used alexa to obtain the alexa ranking and google pr. The xhr requests on the client and server respectively use the xhr requests on the server, the request must be for pages of Google and alexa. Therefore, cross-domain requests are required to use xhr requests on the server.
Garbled Problem
Garbled text is also a common problem for ajax applications.
The charset declared by meta must be consistent with the charset returned by the requested page. It is best to set the output encoding in the request page.
Asp: response. charset = "gb2312 or UTF-8" asp.net: response. charset = "gb2312 or UTF-8" php: header ("charset = gb2312 or UTF-8 ")
The encoding of the physical file storage must be consistent with that of the meta statement. If meta is set to gb2312, the physical storage is encoded as ansi. If it is UTF-8, it is stored as UTF-8 encoding. For asp, if the encoding is UTF-8, remember to set
Session.CodePage=65001Response.CharSet="utf-8"
Because the default processing encoding of asp in domestic servers is gb2312
Synchronization problems
The problem is described as follows:
Function callServerByPost (url, data, fun) {var http_request = null; if (window. activeXObject) http_request = new ActiveXObject ("Microsoft. XMLHTTP ");} else if (window. XMLHttpRequest) http_request = new XMLHttpRequest (); if (! Http_request) {alert ('Giving up: Cannot create an XMLHTTP instance'); return false;} http_request.onreadystatechange = fun; http_request.open ("POST", url, true ); http_request.setrequestheader ("Content-length", data. length); http_request.setRequestHeader ("Content-Type", "application/x-www-form-urlencoded; charset = UTF-8"); http_request.send (data ); // Transfer data} function ajax_post (url, data) {url = url + "? T = "+ new Date (); callServerByPost (url, data, function fns () {if (http_request.readyState = 4) {if (http_request.status = 200) {return http_request.responseText; // when debugging, http_request.responseText has a value but cannot receive it outside.} else {alert ("your request data is wrong") ;}}});} function getData () {var url = "ajax_server.aspx"; var data = "name = ljp & pwd = ljp"; var t = ajax_post (url, data); alert (t ); // undefined ===============================}
Why is this problem ?? Because the code var t = ajax_post (url, data) in getData is executed, because asynchronous is specified, http_request.send (data) in callServerByPost ); // The message transfer statement will not interrupt the execution of other js code, so the next code in getData will be executed, that is, alert (t), so undefined will appear.
In fact, not only does ajax asynchronous cause undefined problems. Take a closer look at the code var t = ajax_post (url, data); The t variable accepts the returned value of ajax_post, but the ajax_post function does not use return to return any value, therefore, undefined is returned by default.
You will say that I didn't use return http_request.responseText here; // it is clear that http_request.responseText has a value but cannot receive it outside of the system? As you can see, it is a state conversion function. It makes no sense to return any value. It only processes the ajax state. Who do you return the value? How can this problem be solved? One is synchronous transmission, the other is to use global variables to accept ajax return values during asynchronous processing, and assign values to global variables in the state conversion function.
When using asynchronous + global variables, note that you do not need to use global variables or undefined before ajax returns. The following describes the synchronization solution. Asynchronous + global variable solution read this article
Function callServerByPost (url, data, fun) {var http_request = null; if (window. activeXObject) http_request = new ActiveXObject ("Microsoft. XMLHTTP ");} else if (window. XMLHttpRequest) http_request = new XMLHttpRequest (); if (! Http_request) {alert ('Giving up: Cannot create an XMLHTTP instance'); return false;} // http_request.onreadystatechange = fun; // no longer need to process functions during synchronization ....... Http_request.open ("POST", url, false); // synchronize http_request.setrequestheader ("Content-length", data. length); http_request.setRequestHeader ("Content-Type", "application/x-www-form-urlencoded; charset = UTF-8"); http_request.send (data); // transfer data return http_request.responseText; // This can be returned directly during synchronization, because it will prevent other code execution} function ajax_post (url, data) {url = url + "? T = "+ new Date (); return callServerByPost (url, data, null); // callback is not required and the return value of callServerByPost is directly returned} function getData () {var url = "ajax_server.aspx"; var data = "name = ljp & pwd = ljp"; var t = ajax_post (url, data); alert (t ); // undefined will not be output here ............, however, if the network is slow, the browser will be suspended ..}
Finally, put the self-written ajax object application pool program
String. prototype. trim = function () {return this. replace (/$ \ s * | \ s * $/g, '');} var Showbo = {author: 'showbo'}; // obtain the json object showbo. getJson = function (v) {if (typeof (v) = 'string') return eval ('+ v +'); else return v ;} // obtain the Showbo object by id. $ = function (Id) {if ('object' = typeof (Id) return Id; else if ('string' = typeof (Id) return document. getElementById (Id); else return null;} Showbo. isIE = !! Document. all; // XMLHttpRequestif (Showbo. isIE) window. XMLHttpRequest = function () {var acX = ['msxml2. xmlhttp.5.0 ', 'msxml2. xmlhttp.4.0 ', 'msxml2. xmlhttp.3.0 ', 'msxml2. xmlhttp ', 'Microsoft. xmlhttp '], Xhr; for (var I = 0; itry {Xhr = new ActiveXObject (acX [I]); return Xhr;} catch (e) {} return false ;} // ajax application pool Showbo. ajax = {pools: [] // array for storing ajax objects, getObject: function () {// obtain ajax objects from the array, create an ajax object for (var I = 0; I <this. Pools. length; I ++) if (this. pools [I]. readyState = 0 | this. pools [I]. readyState = 4) return this. pools [I]; this. pools [this. pools. length] = new XMLHttpRequest (); return this. pools [this. pools. length-1] ;}, send: function (cfg) {/* cfg example {url: 'requested page', params: 'key-value pair, note not a json object ', method: 'Post/get. If this parameter is specified, the default value is get'. success: the callback function for success, failure: the callback function for failure, and otherParams: other parameters provided to the callback function, which can be a json object}. The callback function parameter for success or failure is (the current xhr object, o in the configuration file) TherParams) */if (! Cfg |! Cfg. url) throw ("configuration file not set! "); Var method = cfg. method, asy =" boolean "= typeof (cfg. asy )? Cfg. asy: true; if (! Method | method! = "Post") method = "get"; if (method. toLocaleLowerCase () = 'get') {var _ dc = new Date (). getTime (); // Add a timestamp to prevent the cache cfg in IE. params = cfg. params? Cfg. params + '& _ dc =' + _ dc: '_ dc =' + _ dc; if (cfg. url. indexOf ("? ")! =-1) cfg. url + = "&" + cfg. params; else cfg. url + = "? "+ Cfg. params; cfg. params = null;} else if (! Cfg. params) cfg. params = ''; var o = this. getObject (); if (! O) throw ("cannot Create ajax object! "); O. open (method, cfg. url, asy); if (method. toLocaleLowerCase () = 'post') o. setRequestHeader ("content-type", "application/x-www-form-urlencoded"); o. send (cfg. params); o. onreadystatechange = function () {if (o. readyState = 4) {if (o. status = 200 | o. status = 0) {if ("function" = typeof (cfg. success) cfg. success (o, cfg. otherParams);} else if ("function" = typeof (cfg. failure) cfg. failure (o, cfg. otherParams );}}}}