Ajax problem summary

Source: Internet
Author: User

Basic =================================================== ======
1. 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 random number to make the url unique so that no ie
Or change to post for submission.
Xhr. open ("get", "xxxx. aspx? _ Dc = "+ new Date (). getTime (), true );

2. 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 won't work in ff because ie is case insensitive and ff is case sensitive.
The standard format is if (xhr. readyState = 4). Similarly, there are attributes responseText, responseXML, and status.
Also, the status conversion function xhr. onreadystatechange must be in lowercase.

3. ajax status 0
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:
Copy codeThe Code is 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.
4. responseXML problems.
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 the 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
Copy codeThe Code is as follows:
<Showbo>
<Item> 1 item>
<Item> 2 item>
<Item> 3 item>
<Item> 4 item>
</Showbo>

Test.html
Copy codeThe Code is as follows:
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); // output in ie is 0, and output in ff 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:
Copy codeThe Code is as follows:
Xhr. onreadystatechange = function (){
If (xhr. readyState = 4 ){
If (xhr. status = 200 | xhr. status = 0 ){
Var doc = xhr. responseXML;
If (document. all & xhr. status = 0) {// restructured 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 );
}
}

5. Note the following when submitting a post request.
1) when submitting a post request, set the content-type to "application/x-www-form-urlencoded" so that the request/request can be used on the 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.
2) 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 ....
6. I forgot to sum up another question.
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.
You can refer to the following solutions.
Cross-origin AJAX Solution
One released not long ago
Use alexa and google APIs to obtain the alexa ranking and google pr, and use xhr requests on the client and server respectively.
The xhr request on the server is used. The request must be for Google and alexa pages. Therefore, xhr requests on the server must be used for cross-domain requests.
Garbled problem ================================================= ======
Garbled text is also a common problem for ajax applications.
1) 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 ")
2) the encoding of the physical storage of the file 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
<% @ Language = "vbscript" codepage = "65001" %>
Copy codeThe Code is as follows:
'Prevent Chinese garbled characters when asp uses UTF-8 encoding
Session. CodePage = 65001
Response. CharSet = "UTF-8"

Because the default processing encoding of asp in domestic servers is gb2312
For asp.net, when meta is set to gb2312, it is best to set
Copy codeThe Code is as follows:
<Globalization requestEncoding = "gb2312" responseEncoding = "gb2312"/>

And set Response. CharSet = "gb2312" before outputting Chinese characters ";
Because the default asp.net encoding is UTF-8
3) Use escape/encodeURI/encodeURIComponent to encode the sent Chinese to dynamic pages. We recommend that you use encodeURIComponent.
For more js encoding information, refer to this article.
Js url encoding Functions
For php, there is another problem that needs to be decoded at the server point. You can refer to the discussion in this article.
A php query is written, but Chinese characters cannot be uploaded.
4) if 1-2 pairs are correct but garbled characters still occur when receiving the information sent by the server, try to use XML as the information carrier, and then use responseXML to analyze the returned xml file. Because ajax originally uses xml as the information carrier ...... Ajax English names are originally "asynchronous javascript and xml" [asynchronous javascript and xml]
If the xml file is not parsed, refer to this article.
Summary of XML parsing methods using JavaScript
The following are some articles and solutions with garbled code on csdn. If not, check whether they are exactly the same as yours.
In FireFox, the Chinese string transmitted by asp.net + AJAX is garbled on the server !!!!
Ask ajax to return garbled characters
The above two are listed. To find more and view the query connection, ajax garbled.
Http://so.csdn.net/bbsSearchResult.aspx? Q = ajax + % e4 % b9 % b1 % e7 % a0 % 81 & p = 0
Synchronization problem =================================================== the problem is described as follows, problem: Problem
Copy codeThe Code is 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); // transfers 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 be received outside
} Else {
Alert ("your request data is incorrect ");
}
}
});
}
Function getData (){
Var url = "ajax_server.aspx ";
Var data = "name = ljp & pwd = ljp ";
Var t = ajax_post (url, data );
Alert (t); // The 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 return http_request.responseText is not used here; // when debugging, it is clear that http_request.responseText already has a value, but it cannot receive the returned value 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 ????? No.
How can this problem be solved?
One is synchronous transmission.
One is to use global variables for asynchronous processing to accept ajax return values 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
Why can't the array be passed in as a parameter?
Copy codeThe Code is 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; // no longer need to process functions during synchronization .......
Http_request.open ("POST", url, false); // change to synchronous.
Http_request.setrequestheader ("Content-length", data. length );
Http_request.setRequestHeader ("Content-Type", "application/x-www-form-urlencoded; charset = UTF-8 ");
Http_request.send (data); // transfers data
Return http_request.responseText; // This can be returned directly during synchronization because it will prevent other code from being executed.
}
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); // No undefined will be output here... but if the network is slow, the browser will be suspended ..
}

The following describes the similarities and differences between ff and ie status conversion. For more information, see
AJAX onreadystatechange in Firefox
Put a self-written ajax class library ~~~~~ O (sort _ messages) O Haha ~~~~~ Finished
Copy codeThe Code is as follows:
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 object by id
Showbo. $ = function (Id) {if ('object' = typeof (Id) return Id; else if ('string' = typeof (Id) return document. getElementById (Id); else return null ;}
Showbo. IsIE = !! Document. all;
// Extended XMLHttpRequest in IE
If (Showbo. IsIE &&! Window. XMLHttpRequest) 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: [] // an array for storing ajax objects
, GetObject: function () {// obtain the ajax object from the array. If no ajax object is returned, a new ajax object is created.
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 that it is 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
, OtherParams: Other parameters provided to the callback function, which can be json objects
}
The callback function parameter for success or failure is (the current xhr object, otherParams in the configuration file)
*/
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 cache in IE
Cfg. 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 );
}
}
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.