Ajax Problem Summary Compare total _ajax correlation

Source: Internet
Author: User
The basic ============================================
1, the most classic is the cache problem under IE.
If you are using GET, then there is a caching problem under IE. Causes the code to execute only once. The solution is to add a timestamp or random number so that the URL becomes unique so that IE does not appear
or a post submission instead of a cache problem.
Xhr.open ("Get", "xxxx.aspx?_dc=" +new Date (). GetTime (), true);

2,ajax The case of object properties
In the Web browser, such as FF, it is sensitive to capitalization. Such as
if (xhr.readystate==4) This type of writing, under IE is set up, but under the FF is not feasible, because IE is not case-sensitive, FF is the size of the case.
The standard is written as if (xhr.readystate==4), with the same attribute responsetext,responsexml,status.
Also has the state conversion function Xhr.onreadystatechange, should note all is lowercase

3,ajax Status 0 problem
Sometimes when testing Ajax code, add xhr.status==200 judgment, always do not execute xhr.status==200 code, this need attention.
XHR.STATUS==200 is to browse through the server, and the server page does not have an error or turn to return 200 state, this state and you access the page through the browser when the server defined the same state.
Drag directly into the browser to browse the results or double-click the HTML page to run, when there is no error, the Xhr.status at this time is 0, not 200.
So you can add a xhr.status==0 judgment. As follows
Copy Code code as follows:

if (xhr.status==200| | xhr.status==0) {
Alert (' OK ');
}

Drag directly into the browser to browse the results or double-click to run the HTML page, there is a problem, if the request is an XML file, it is assumed to use the Responsexml property to return xmldom, but in IE can not return the XMLDOM attribute, how to solve it, Look at the responsexml question below.
4,responsexml problem.
To use the Responsexml property, the request is an XML file or a dynamic page with the response header "Text/xml" set. Be aware that if you are requesting a dynamic page, you must not forget to set contenttype as "Text/xml"!!!!!!!! Remember ~~~~~~
ASP for response.contenttype= "text/html"
asp.net for response.contenttype= "text/html";
PHP is header ("content-type:text/xml;");
In IE, there is a problem, drag directly into the browser or double-click to run HTML preview effect, the requested even the XML file, using Responsexml can not return XMLDOM.
We will know it under test, as follows
Showbo.xml
Copy Code code as follows:

<showbo>
<item>1item>
<item>2item>
<item>3item>
<item>4item>
</showbo>

Test.html
Copy Code code as follows:

function Getajax () {
if (window. XMLHttpRequest) return to New XMLHttpRequest ();
else if (window. ActiveXObject) return to 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)//in IE output is 0, under FF is 4. It seems that the XML tree structure is not generated under IE, the specific reason to ask Ms.
}
else alert (' ERROR \ 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 re-establish the tree structure of the XML, as follows
Copy Code code as follows:

Xhr.onreadystatechange=function () {
if (xhr.readystate==4) {
if (xhr.status==200| | xhr.status==0) {
var doc=xhr.responsexml;
Refactor the XML tree structure if (document.all&&xhr.status==0) {//is IE and is directly in the browser
Doc=new ActiveXObject ("Microsoft.XMLDOM");
Doc.loadxml (Xhr.responsetext);
Doc=doc.documentelement;
}
var item=doc.getelementsbytagname ("item");
alert (item.length);
}
else alert (' ERROR \ n \ +xhr.status ');
}
}

5, to be aware of when submitting a post.
1 when submitting for post, be aware that you want to set Content-type to "application/x-www-form-urlencoded" so that you can use it on a dynamic page request/request.form/ The Request.QueryString object gets the value through the key, otherwise you have to use 2 data, and then analyze the 2 feed data to generate the string object, and then get the corresponding value using the regular or something.
2 You need to open in order to use the Xhr.setrequestheader method, or error.
Xhr.open ("Post", "xxxx.aspx", true);
Xhr.setrequestheader ("Content-type", "application/x-www-form-urlencoded");//here ....
6. One more question to forget is that the problem of cross domain
If the requested page is not the current site, it spans the domain, and the best solution is the server-side XHR request
You can refer to the solution below
Ajax cross-Domain problem resolution
A recent release of
Use the Alexa,google API to get Alexa rankings and Google PR, using both client and server-side XHR requests
is to use the server-side XHR request, should be for the Google and Alexa pages, so cross-domain, need to use server-side XHR request.
Garbled problem ============================================
For AJAX applications, garbled is also a recurring problem.
1 The charset of the Meta Declaration is consistent with the charset returned by the requested page. It is a good idea to set the output code again in the requested 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 file physical storage encoding should be consistent with the Meta Declaration encoding. If meta is specified as gb2312, the physical storage is encoded as ANSI. If it is utf-8, it is stored as a utf-8 encoding.
For ASP, if you specify the encoding as Utf-8, remember to set the
<% @language = "VBScript" codepage= "65001"%>
Copy Code code as follows:

' Prevents the ASP to use UTF-8 encoding when the Chinese appears garbled
session.codepage=65001
response.charset= "Utf-8"

Because the ASP in the domestic server default processing code for GB2312
For ASP.net, when the meta is set to gb2312, it is best to set the Web.config file
Copy Code code as follows:

<globalization requestencoding= "gb2312" responseencoding= "gb2312"/>

, and set response.charset= "gb2312" before outputting Chinese;
Because the default encoding for ASP.net is utf-8
3 Send Chinese to dynamic page using escape/encodeuri/encodeuricomponent encoding. Recommended use of encodeURIComponent.
More JS code information to view this article
JS URL encoding function
For PHP, there is also a problem that needs to be decoded at the server point. You can see the discussion in this article.
Write a PHP query, but it is not the Chinese.
4 If 1-2 are all right, but when the information sent by the server is still garbled, try XML as an information carrier, and then use Responsexml to analyze the next-pass XML file. Because Ajax is the original use of XML as an information carrier ... Ajax English is originally "Asynchronous JavaScript and XML" "Asynchronous JavaScript and XML"
If you do not parse the XML file, you can refer to this article
A summary of JavaScript parsing XML method
Here are some csdn on the occurrence of garbled articles and solutions, has not been resolved to see whether and you are the same.
In the Firefox browser Asp.net+ajax transmission of Chinese strings to the server-side after the problem of garbled!!!!
Ask Ajax to return garbled
On the list above two, to find more, see this query connection, are Ajax garbled problem.
Http://so.csdn.net/bbsSearchResult.aspx?q=ajax+%e4%b9%b1%e7%a0%81&p=0
Synchronization problem ============================================ The problem is described below, the problem comes from http://topic.csdn.net/u/20090630/16/ d4d07596-65da-430c-8e89-cae60e25e03c.html, streamlining the code to create Ajax
Copy Code code 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)//data transmission
}
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;//here when the debugging is clearly http_request.responsetext already have value but outside but can't receive
} else {
Alert ("You request data is wrong");
}
}
});
}
function GetData () {
var url= "ajax_server.aspx";
var data= "NAME=LJP&AMP;PWD=LJP";
var t=ajax_post (Url,data);
Alert (t);//pop up undefined ============================= here
}

Why is there such a problem?? Because of the code var t=ajax_post (url,data) in the execution GetData, http_request.send (data) in Callserverbypost because of the specified asynchronous, and/or transmission This sentence does not interrupt the execution of other JS code, so will continue to execute the next code in GetData, is alert (t), so will appear undefined.
In fact, it is not only the Ajax asynchronous lead to the emergence of undefined problems. Look carefully at the code var t=ajax_post (url,data); the t variable is accepted as the Ajax_post return value, but the Ajax_post function does not return any value using returns, so the default is to return undefined.
You would say I'm not using the return http_request.responsetext;//here when the debugging is clearly http_request.responsetext already have a value but not in the outside to receive back?????????????????????????
You see clearly, that is the state conversion function, you return any value is meaningless, he just deal with the state of Ajax, you return the value to whom? Isn't it.
How to solve this problem?
One is to send synchronously instead
One is to use global variables to accept Ajax return values for Asynchrony, and to assign values to global variables in state transition functions.
When using asynchronous + global variables, be aware that you don't have to use global variables or undefined before Ajax returns.
The following is a solution for synchronization. Solutions to asynchronous + global variables look at this article.
Why is an array passed in as a parameter to get the value out?
Copy Code code 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; Processing functions are no longer required for synchronization ....
Http_request.open ("POST", url, false);//Sync instead
Http_request.setrequestheader ("Content-length", data.length);
Http_request.setrequestheader ("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
Http_request.send (data)//data transmission
Return http_request.responsetext;//can be returned directly when synchronizing, because it prevents other code from executing
}
function Ajax_post (url,data) {
url=url+ "t=" +new Date ();
Return Callserverbypost (url,data,null);/do not need to pass the callback and return the Callserverbypost value directly
}
function GetData () {
var url= "ajax_server.aspx";
var data= "NAME=LJP&AMP;PWD=LJP";
var t=ajax_post (Url,data);
Alert (t);//This will not output undefined ..... , but if the internet is slow, the browser will suspend animation.
}

The following is an introduction to the similarities and differences between FF and IE state transitions, with an interest in the reference
Ajax onreadystatechange problem under Firefox
Finally put a write your own Ajax class library ~~~~~o (∩_∩) O haha ~~~~~ finished
Copy Code code as follows:

String.prototype.trim=function () {return this.replace (/$\s*|\s*$/g, ');}
var showbo={author: ' Showbo '};
Get the JSON object
Showbo.getjson=function (v) {if (typeof (v) = = ' string ') return eval (' (' +v+ ') '), Else return v}
Get an object from an 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 under 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:[]//stores an array of Ajax objects
, Getobject:function () {//Gets the Ajax object from the array, and creates a new Ajax object if it is not returned
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 sample
{
URL: ' Requested page '
, params: ' key value pair, note not JSON object '
, method: ' Post/get, if specified, default to get '
, success: callback function at time of success
, Failure: callback function when failed
, Otherparams: Additional arguments provided to the callback function that can be the JSON object
}
The successful or failed callback function argument is (the current XHR object, the 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 ()//timestamp prevents cache under IE browser
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 ("Failed to create an 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.