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

How to solve the caching problem in AJAX

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

Share

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

This article will explain in detail how to solve the cache problem in AJAX. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

Ajax is used to do a project. At first, I feel good, but then I find a problem, such as deleting an item. After it is restored, it cannot be deleted again.

We had to wait for a while, but it turned out that it was the IE cache.

The AJAX cache page is a problem that must be encountered by people who are new to AJAX, and the key person causing this problem is Ie....

After finding a lot of information on the Internet, sum it up.

1: by adding a random function to the page requested by AJAX, we can use the random time function

Add t=Math.random () to the URL sent by javascript

Of course, instead of copying t=Math.random () directly after URL, it should look like this: URL+ "&" + "t =" + Math.random ()

2: add XMLHttpRequest.setRequestHeader ("If-Modified-Since", "0") before XMLHttpRequest sends the request

Normally, the XMLHttpRequest here will not be used directly.

You should be able to find code like this.

XXXXX.send (YYYYYY)

So, turn it into

XXXXX.setRequestHeader ("If-Modified-Since", "0")

XXXXX.send (YYYYYY)

The second method feels good.

Two methods of clearing cache by ajax

The first kind:

Add to the template

The second kind:

Url plus random number variable

[introduction to AJAX]

Ajax is a Web application development method that uses client script to exchange data with Web servers. Web pages can be updated dynamically without interrupting the interaction process for re-tailoring. With Ajax, users can create a direct, highly available, richer, and more dynamic Web user interface close to local desktop applications.

Asynchronous JavaScript and XML (AJAX) are not new technologies, but use several existing technologies-including cascading stylesheets (CSS), JavaScript, XHTML, XML, and Extensible style language transformations (XSLT)-to develop Web applications that look and operate like desktop software.

[AJAX implementation principle]

An Ajax interaction starts with a JavaScript object called XMLHttpRequest. As the name implies, it allows a client script to execute the HTTP request and will parse a server response in XML format. The first step in Ajax processing is to create an instance of XMLHttpRequest. Use the HTTP method (GET or POST) to process the request and set the target URL to the XMLHttpRequest object.

When you send a HTTP request, you don't want the browser to hang and wait for a response from the server. Instead, you want to continue to respond to the user's interface interaction through the page and process them after the server response actually arrives. To do this, you can register a callback function with XMLHttpRequest and dispatch XMLHttpRequest requests asynchronously. Control is immediately returned to the browser, and when the server response arrives, the callback function will be called.

[practical application of AJAX]

1. Initialize Ajax

Ajax actually calls the XMLHttpRequest object, so first we must call this object, and we build a function that initializes the Ajax:

The copy code is as follows:

/ * *

* initialize a xmlhttp object

, /

Function InitAjax ()

{

Var ajax=false

Try {

Ajax = new ActiveXObject ("Msxml2.XMLHTTP")

} catch (e) {

Try {

Ajax = new ActiveXObject ("Microsoft.XMLHTTP")

} catch (E) {

Ajax = false

}

}

If (! ajax & & typeof xMLHttpRequestrated undefined) {

Ajax = new XMLHttpRequest ()

}

Return ajax

}

2. Ajax uses Get method

Now let's take the first step to execute a Get request to add the data we need to get / show.php?id=1, so what should we do?

Suppose there is a link: news 1, when I click on the link, I do not want to refresh to see the contents of the link, then what should we do?

/ / change the link to:

/ / and set a layer to receive news, and set it not to display:

At the same time, construct the corresponding JavaScript function:

The copy code is as follows:

Function getNews (newsID)

{

/ / if the parameter newsID is not passed in

If (typeof (newsID) = = 'undefined')

{

Return false

}

/ / the URL address where Ajax is required

Var url = "/ show.php?id=" + newsID

/ / get the location of the news display layer

Var show = document.getElementById ("show_news")

/ / instantiate Ajax object

Var ajax = InitAjax ()

/ / use Get to make requests

Ajax.open ("GET", url, true)

/ / get the execution status

Ajax.onreadystatechange = function () {

/ / if the execution status is normal, then assign the returned content to the layer specified above

If (ajax.readyState = = 4 & & ajax.status = = 200) {

Rao [XSS _ clean] = ajax.responseText

}

}

/ / send empty

Ajax.send (null)

}

This method is suitable for any element on the page, including the form, etc., in fact, in the application, the operation of the form is more, for the form, more use of the POST way, which will be described below.

3. Ajax uses POST method

In fact, the POST mode is similar to the Get mode, except that there is a slight difference in the implementation of Ajax. Let's talk about it briefly.

Suppose there is a form in which the user enters data, and we save the user's data to the database without refreshing and give the user a successful hint.

The copy code is as follows:

/ / build a form that does not require attributes such as action or method, and is all handled by ajax.

Name:

Age:

Gender:

/ / build a layer that accepts the returned information:

We see that there is no need to submit target and other information in the form form above, and the type of submit button is only button, so all operations are performed by the saveUserInfo () function in the onClick event. Let's describe this function:

The copy code is as follows:

Function saveUserInfo ()

{

/ / get the information layer of receiving and returning

Var msg = document.getElementById ("msg")

/ / get form objects and user information values

Var f = document.user_info

Var userName = f.user_name.value

Var userAge = f.user_age.value

Var userSex = f.user_sex.value

/ / receive the URL address of the form

Var url = "/ save_info.php"

/ / the value of POST is required, and each variable is joined by &

Var postStr = "user_name=" + userName + "& user_age=" + userAge + "& user_sex=" + userSex

/ / instantiate Ajax

Var ajax = InitAjax ()

/ / Open the connection via Post

Ajax.open ("POST", url, true)

/ / define the HTTP header information of the transferred file

Ajax.setRequestHeader ("Content-Type", "application/x-www-form-urlencoded")

/ / send POST data

Ajax.send (postStr)

/ / get the execution status

Ajax.onreadystatechange = function () {

/ / if the execution status is successful, the return information is written to the specified layer

If (ajax.readyState = = 4 & & ajax.status = = 200) {

MSG [XSS _ clean] = ajax.responseText

}

}

}

4. Asynchronous callback (pseudo-Ajax mode)

In general, using Get, Post way of Ajax we can solve the current problem, but the application complexity, of course, we may encounter in the development can not use Ajax, but we also need to simulate the effect of Ajax, then we can use pseudo-Ajax way to achieve our requirements.

The general principle of pseudo-Ajax is that we are still ordinary form submissions or something, but we target the value of the submission as a floating frame so that the page does not refresh, but, uh, we need to see our execution result, of course, we can use JavaScript to simulate the prompt message, but this is not true, so we need our execution result to call back asynchronously Tell us what the result of the implementation is.

Suppose our requirement is to upload a picture, and we need to know the status of the picture after upload, such as whether the upload is successful, whether the file format is correct, whether the file size is correct, and so on. Then we need our target window to return the execution result to our window so that we can successfully simulate the process of an Ajax call.

The following code is a little more and involves Smarty template technology. If you don't know much about it, please read the relevant technical materials.

Upload file: upload.html

The copy code is as follows:

/ / upload the form and specify that the target attribute is floating frame iframe1

Select the picture to upload:

/ / the layer that displays the prompt

/ / floating frame used to make the target window

{if $upload_msg! = ""}

CallbackMessage ("{$upload_msg}")

{/ if}

/ / callback JavaScript function, which is used to display information in the parent window

Function callbackMessage (msg)

{

/ / Open the layer where the parent window displays messages

Parent.document.getElementById ("message") .style.display = "block"

/ / write down the messages obtained in this window

Parent.document.getElementById ("message") [xss_clean] = msg

/ / and set to automatically turn off the message display of the parent window after 3 seconds

SetTimeout ("parent.document.getElementById ('message'). Style.display =' none'", 3000)

}

This is the end of the article on "how to solve the caching problem in AJAX". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

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