Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the problems with ajax

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly shows you "what are the ajax problems", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "what are the ajax problems" this article?

Basic =

1, the most classic is the cache problem under ie.

If you are using get, there is a caching problem under ie. Causes the code to be executed only once. The solution is to add a timestamp or random number to make the url unique, so that there is no ie.

There is a cache problem under, or change it to post submission.

Xhr.open ("get", "xxxx.aspx?_dc=" + new Date (). GetTime (), true)

2 the case problem of the properties of the moment Ajax object

In W3C browsers, such as ff, it is case sensitive Such as

If (xhr.readystate==4) is true in ie, but it doesn't work in ff, because ie is case-insensitive and ff is case-sensitive.

The standard way of writing is if (xhr.readyState==4), which also has the attribute responseText,responseXML,status.

There is also the state transition function xhr.onreadystatechange. Note that it is all lowercase.

3The problem of Ajax status 0

Sometimes when testing the ajax code, after adding the xhr.status==200 judgment, the xhr.status==200 code has not been executed, this needs to be noted.

Xhr.status==200 is browsed through the server, and the server page is returned when there is no error or redirection, which is consistent with the state defined by the server when you access the page through the browser.

If you drag directly to the browser or double-click to run the html page, when no error occurs, the xhr.status is 0, not 200.

So you can add an extra xhr.status==0 judgment. As follows

The copy code is as follows:

If (xhr.status==200 | | xhr.status==0) {

Alert ('ok')

}

Directly into the browser browsing results or double-click to run the html page, there is another problem, if the request is a xml file, it is taken for granted to use the responseXML property to return xmlDom, but in ie can not return the xmlDom property, how to solve it, look at the following responseXML problem.

4ResponseXML problem.

To use the responseXML attribute, request a xml file or a dynamic page with the response header set to "text/xml". Note that if you are requesting a dynamic page, don't 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;")

There is a problem under ie, when dragging directly to the browser or double-clicking to run the html preview effect, even if the request is a xml file, using responseXML will not return xmldom.

You will know after the test, as follows

Showbo.xml

The copy code is as follows:

1item >

2item >

3item >

4item >

Test.html

The copy 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); / / the output is 0 in ie and 4 in ff. It seems that the tree structure of xml is not generated under ie. The specific reason is to ask ms.

}

Else alert ('error occurred\ n\ n'+xhr.status)

}

}

Xhr.open ("get", "showbo.xml?_dc=" + new Date (). GetTime (), true)

Xhr.send (null)

The solution is to re-establish the tree structure of the xml using the microsoft.xmldom object, as follows

The copy code is as follows:

Xhr.onreadystatechange=function () {

If (xhr.readyState==4) {

If (xhr.status==200 | | xhr.status==0) {

Var doc=xhr.responseXML

Reconstruct the tree structure of xml when if (document.all&&xhr.status==0) {/ / is ie and is pushed directly into 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 occurred\ n\ n'+xhr.status)

}

}

5, what you should pay attention to when submitting for post.

1) if you submit for post, be careful to set content-type to "application/x-www-form-urlencoded", so that you can use the request/request.form/request.querystring object to get the value through the key in the dynamic page, otherwise you have to use binary data, and then analyze the binary data to generate a string object and use regular what to get the corresponding value.

2) the xhr.setRequestHeader method cannot be used until after open, otherwise there will be an error.

Xhr.open ("post", "xxxx.aspx", true)

Xhr.setRequestHeader ("content-type", "application/x-www-form-urlencoded"); / / here.

6. There's another problem that I forgot to summarize, the cross-domain problem.

If the requested page is not from the current site, it is cross-domain. The best solution is the server-side xhr request.

You can refer to the following solution

Solution to the Cross-domain problem of AJAX

One released not long ago.

Use alexa,google 's api to get alexa ranking and google pr, using client-side and server-side xhr requests respectively

The server-side xhr request is used, because the request is the Google and alexa page, so cross-domain, you need to use the server-side xhr request.

Garbled problem =

Garbled code is also a frequent problem for ajax applications.

1) the charset declared by meta should be the same as the charset returned by the requested page. It is best to set the output code 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 physical storage encoding of the file should be consistent with the encoding declared by meta. If meta is specified as gb2312, the physical storage is encoded as ansi. If utf-8, it is stored as utf-8 encoding.

For asp, if you specify the encoding as utf-8, remember to set the

The copy code is as follows:

'prevent garbled Chinese characters when asp uses utf-8 coding

Session.CodePage=65001

Response.CharSet= "utf-8"

Because the default processing code of asp in domestic servers is gb2312.

For asp.net, when meta is set to gb2312, it is best to set the

The copy code is as follows:

And set Response.CharSet= "gb2312" before outputting Chinese

Because the default encoding of asp.net is utf-8

3) use escape/encodeURI/encodeURIComponent encoding when sending Chinese to dynamic pages. EncodeURIComponent is recommended.

See this article for more js coding information.

JS URL coding function

There is another problem for php, which needs to be decoded at the server point. You can read the discussion in this article.

I wrote a php query, but I just couldn't send it out in Chinese.

4) if both 1-2 are matched, but there are still garbled codes when accepting the information sent by the server, try XML as the information carrier, and then use responseXML to analyze the returned xml file. Because ajax originally uses xml as the information carrier. The English name of ajax is originally "Asynchronous javascript and xml" [asynchronous javascript and xml]

If you can't parse the xml file, you can refer to this article

Summary of the methods of parsing XML by JavaScript

Here are some garbled articles and solutions on csdn that haven't been solved yet to see if they are the same as yours.

The problem of garbled Chinese strings transmitted by asp.net+AJAX to the server in the FireFox browser!

Ask ajax to return garbled code.

List the above two, to find more, check this query connection, it is the problem of garbled code in ajax.

Http://so.csdn.net/bbsSearchResult.aspx?q=ajax+%e4%b9%b1%e7%a0%81&p=0

Synchronization problem = the problem is described as follows. The problem comes from http://topic.csdn.net/u/20090630/16/d4d07596-65da-430c-8e89-cae60e25e03c.html, which simplifies the code for creating ajax.

The copy 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); / / transmit 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) {

When return http_request.responseText;// is debugged here, the http_request.responseText already has a value, but it cannot be received outside.

} else {

Alert ("there is something wrong with your request data")

}

}

});

}

Function getData () {

Var url= "ajax_server.aspx"

Var data= "name=ljp&pwd=ljp"

Var t=ajax_post (url,data)

Alert (t); / / pops up here undefined = =

}

Why did this problem arise? Because when the code var t=ajax_post (url,data); in getData is executed, the sentence http_request.send (data) in callServerByPost (data); / / transfers data does not interrupt the execution of other js code, so it continues to execute the next line of code in getData, which is alert (t), so undefined occurs.

In fact, it is not just ajax asynchronism that causes undefined problems. Take a closer look at the code var t=ajax_post (url,data); the t variable accepts the return value of ajax_post, but return is not used in the ajax_post function to return any value, so the default is to return undefined.

Would you say that I am not using return http_request.responseText;// here when debugging http_request.responseText already has a value but can not receive a return on the outside?

You can see clearly, that is the state transition function, it is meaningless for you to return any value, it just deals with the state of ajax, who do you return the value to? Isn't it.

How to solve this problem?

One is to send synchronously.

One is to use global variables for asynchronism to accept the return value of ajax and assign values to global variables in the state transition function.

When using asynchronous + global variables, it is important to note that you do not need to use global variables, or undefined, until ajax is returned.

The solution to synchronization is given below. The solution to async + global variables see this article

Why can't you get the value out of the array passed in as a parameter?

The copy 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; / / the handler is no longer needed for synchronization.

Http_request.open ("POST", url, false); / / change to synchronization

Http_request.setrequestheader ("Content-length", data.length)

Http_request.setRequestHeader ("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8")

Http_request.send (data); / / transmit data

You can return directly when return http_request.responseText;// synchronizes, because it prevents other code from executing

}

Function ajax_post (url,data) {

Url=url+ "? t =" + new Date ()

Return callServerByPost (url,data,null); / / No callback is required, and the return value of callServerByPost is returned directly.

}

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 fake it.

}

The following article introduces the similarities and differences between ff and ie state transitions. If you are interested, please refer to them.

AJAX onreadystatechange problem under Firefox

Finally, put a self-written ajax class library ~ O (∩ _ ∩) O ~ over

The copy code is as follows:

String.prototype.trim=function () {return this.replace (/ $\ s* |\ smarker GJM');}

Var Showbo= {author:'showbo'}

/ / get the json object

Showbo.getJson=function (v) {if (typeof (v) = = 'string') return eval (' ('+ vested')'); else return v;}

/ / get the object according to id

Showbo.$=function (Id) {if ('object'==typeof (Id)) return Id;else if (' string'==typeof (Id)) return document.getElementById (Id); else return null;}

Showbo.IsIEfolk written document.all

/ / expand XMLHttpRequest under IE

If (Showbo.IsIEpped windows. Xmlhttquest) window.XMLHttpRequest=function () {

Var acX= ['msxml2.xmlhttp.5.0','msxml2.xmlhttp.4.0','msxml2.xmlhttp.3.0','msxml2.xmlhttp','microsoft.xmlhttp'], Xhr

For (var iTunositry {Xhr=new ActiveXObject (ACX [I]); return Xhr;} catch (e) {}

Return false

}

/ / ajax application pool

Showbo.Ajax= {

Pools: [] / / an array that stores ajax objects

, getObject:function () {/ / gets the ajax object from the array, and creates a new ajax object if it is not returned

For (var iTuno Bandi)

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report