Two solutions to Ajax cache problems (IE)

Source: Internet
Author: User
Tags smarty template

I started to think it was good to use Ajax for a project. Then I found a problem, for example, deleting an item. After the project is restored, it cannot be deleted,
You have to wait for a while. Later I learned that it was an issue with IE caching.
The Ajax cache page is a problem that people who are new to Ajax may encounter. The key cause of this problem is ie...
After finding a lot of information on the Internet, let's summarize it.
1: Add a random function after the page of the Ajax request. We can use the random time function.
Add T = math. Random () after the URL sent by JavaScript ()
Of course, instead of directly copying T = math. Random () to the end of the URL, it should be like this: URL + "&" + "t =" + math. Random ();
2: Before XMLHttpRequest sends a request, add XMLHttpRequest. setRequestHeader ("If-modified-since", "0 ")
Generally, XMLHttpRequest won't be used directly.
You should be able to find Code
XXXXX. Send (yyyyyy );
Then, convert it
XXXXX. setRequestHeader ("If-modified-since", "0 ");
XXXXX. Send (yyyyyy );
The second method is quite good.
Two Methods for clearing the cache using Ajax
First:
Add
<Meta HTTP-EQUIV = "Pragma" content = "no-Cache">
<Meta HTTP-EQUIV = "cache-control" content = "no-cache, must-revalidate">
<Meta HTTP-EQUIV = "expires" content = "wed, 26 Feb 1997 08:21:57 GMT">
Second:
Add random number variable to URL
[Ajax Introduction]
Ajax is a Web application development method that uses client scripts to exchange data with Web servers. Web pages can be dynamically updated without interrupting the interaction process and cutting them again. With Ajax, users can create direct, highly available, richer, and more dynamic Web user interfaces close to local desktop applications.
Asynchronous JavaScript and XML (Ajax) are not new technologies. They use several existing technologies, including Cascading Style Sheets (CSS), JavaScript, XHTML, XML, and extensible style language conversion (XSLT), develop web applications that look and operate similar to desktop software.
[Ajax execution principle]
An Ajax interaction starts with a JavaScript Object called XMLHttpRequest. As the name implies, it allows a client script to execute an HTTP request and parse a server response in XML format. The first step in Ajax processing is to create an XMLHttpRequest instance. Use the HTTP method (get or post) to process the request and set the target URL to the XMLHTTPRequest object.
When you send an HTTP request, you do not want the browser to suspend and wait for the response from the server. Instead, you want to continue responding to user interface interactions through the page, and post-processing them after the server response actually arrives. To complete this, you can register a callback function with XMLHttpRequest and asynchronously dispatch the XMLHttpRequest request. The Control Right is immediately returned to the browser. When the server responds, the callback function will be called.
[Ajax application]
1. initialize Ajax
Ajax actually calls the XMLHTTPRequest object. First, we must call this object. We construct an Ajax initialization function:

Copy code The Code is as follows :/**
* Initialize an 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 XMLHttpRequest! = 'Undefined '){
Ajax = new XMLHttpRequest ();
}
Return Ajax;
}

2. Use the get method of Ajax
now we are going to execute a GET request, and add the get/show. php? Id = 1 data, so what should we do?
assume there is a link: News 1 . When I click this link, I don't want to refresh it to see the link content. What should I do?
// change the link to:
// set a news receiving layer, and set it to not display:
at the same time, construct the corresponding JavaScript function: copy Code the code is as follows: function getnews (newsid)
{< br> // If newsid is not passed in
If (typeof (newsid) = 'undefined ')
{< br> return false;
}< br> // URL for Ajax
var url = "/Show. PHP? Id = "+ newsid;
// obtain the position of the news display layer
var show = document. getelementbyid ("show_news");
// instantiate an Ajax object
var Ajax = initajax ();
// use get to request Ajax.
. open ("get", URL, true);
// obtain the execution status
Ajax. onreadystatechange = function () {
// if the execution is normal, the returned content is assigned to the layer specified above
If (Ajax. readystate = 4 & Ajax. status = 200) {
show. innerhtml = Ajax. responsetext;
}< BR >}< br> // sending blank
Ajax. send (null);
}

This method is applicable to any elements in the page, including forms. In fact, there are many form operations in the application. For forms, the POST method is more used, the following is a description.
3. Ajax uses the POST method
In fact, the POST method is similar to the get method, but it is slightly different when Ajax is executed. Let's briefly describe it.
Suppose there is a user input data form, we save the user data to the database without refreshing, and give the user a success prompt.Copy codeThe Code is as follows: // construct a form without the need for attributes such as action and method in the form, which is all done by Ajax.
<Form name = "user_info">
Name: <input type = "text" name = "user_name"/> <br/>
Age: <input type = "text" name = "user_age"/> <br/>
Gender: <input type = "text" name = "user_sex"/> <br/>
<Input type = "button" value = "Submit Form" onclick = "saveuserinfo ()">
</Form>
// Construct a layer for receiving returned information:
<Div id = "MSG"> </div>

We can see that there is no need to submit the target information in the form above, and the type of the submit button is only a button, so all operations are executed by the saveuserinfo () function in The onclick event. Let's describe this function: Copy code The Code is as follows: function saveuserinfo ()
{
// Obtain the accept response information layer
VaR MSG = Document. getelementbyid ("MSG ");
// Obtain the form object and user information value
VaR F = Document. user_info;
VaR username = f. user_name.value;
VaR userage = f. user_age.value;
VaR usersex = f. user_sex.value;
// URL of the received form
VaR url = "/save_info.php ";
// The post value is required to connect each variable through &
VaR poststr = "user_name =" + username + "& user_age =" + userage + "& user_sex =" + usersex;
// Instantiate Ajax
VaR Ajax = initajax ();

// Open the connection through post
Ajax. Open ("Post", URL, true );
// Define the HTTP header information of the transmitted File
Ajax. setRequestHeader ("Content-Type", "application/X-WWW-form-urlencoded ");
// Send post data
Ajax. Send (poststr );
// Obtain the execution status
Ajax. onreadystatechange = function (){
// If the execution status is successful, the returned information is written to the specified layer.
If (Ajax. readystate = 4 & Ajax. Status = 200 ){
MSG. innerhtml = Ajax. responsetext;
}
}
}

4. asynchronous callback (pseudo Ajax)
Under normal circumstances, Ajax using get and post methods can solve the current problem, but the application complexity. Of course, during development, we may encounter a problem where Ajax cannot be used, however, we need to simulate the Ajax effect, so we can use the pseudo Ajax method to achieve our needs.
The general principle of pseudo Ajax is that we are still submitting a common form or something, but we set the submitted value to a floating framework, so that the page will not be refreshed. However, we also need to see our execution results. Of course we can use JavaScript to simulate the prompt information. However, this is not true, so we need our execution results for asynchronous callback, tell us how the execution result is.
Assume that we need to upload an image and know its status, for example, whether the image is uploaded successfully, whether the file format is correct, and whether the file size is correct. Then we need our target window to return the execution result to our window, so that we can smoothly simulate an Ajax call process.
The following code is a little more and involves the smarty template technology. If you do not know much about it, please read the related Technical materials .
Upload File: upload.html Copy code The Code is as follows: // upload a form and specify the target attribute as the floating frame iframe1
<Form action = "/upload. php" method = "Post" enctype = "multipart/form-Data" name = "upload_img" target = "iframe1">
Select the image to upload: <input type = "file" name = "image"> <br/>
<Input type = "Submit" value = "Upload image">
</Form>
// Display the prompt information layer
<Div id = "message" style = "display: none"> </div>
// Floating frame used for the target window
<IFRAME name = "iframe1" width = "0" Height = "0" scrolling = "no"> </iframe>
<? PHP
/* Define a constant */
// Define the MIME format that can be uploaded
Define ("upload_image_mime", "image/pjpeg, image/jpg, image/JPEG, image/GIF, image/X-PNG, image/PNG ");
// Size, in bytes allowed for the image
Define ("upload_image_size", 102400 );
// The image size is measured in KB.
Define ("upload_image_size_kb", 100 );
// Upload path
Define ("upload_image_path", "./upload /");
// Obtain the allowed image format
$ Mime = explode (",", user_face_mime );
$ Is_vaild = 0;
// Traverse all permitted formats
Foreach ($ mime as $ type)
{
If ($ _ FILES ['image'] ['type'] = $ type)
{
$ Is_vaild = 1;
}
}
// Upload the file if the format is correct and the file size does not exceed the size
If ($ is_vaild & $ _ FILES ['image'] ['SIZE'] <= user_face_size & $ _ FILES ['image'] ['SIZE']> 0)
{
If (move_uploaded_file ($ _ FILES ['image'] ['tmp _ name'], user_image_path. $ _ FILES ['image'] ['name'])
{
$ Upload_msg = "image uploaded successfully! ";
}
Else
{
$ Upload_msg = "An error occurred while uploading the image file ";
}
}
Else
{
$ Upload_msg = "failed to upload the image. It may be because the file exceeds". user_face_size_kb. "kb, the image file is empty, or the file format is incorrect ";
}
// Parse the Template File
$ Smarty-> assign ("upload_msg", $ upload_msg );
$ Smarty-> display ("Upload. TPL ");
?>
{If $ upload_msg! = ""}
Callbackmessage ("{$ upload_msg }");
{/If}
// Callback JavaScript function, used to display information in the parent window
Function callbackmessage (MSG)
{
// Open the message layer in the parent window
Parent.doc ument. getelementbyid ("message"). style. Display = "Block ";
// Write the messages obtained in this window
Parent.doc ument. getelementbyid ("message"). innerhtml = MSG;
// Automatically close the display of messages in the parent window after being set to 3 seconds
SetTimeout ("parent.doc ument. getelementbyid ('message'). style. Display = 'none'", 3000 );
}

[Conclusion]
This is a very good web development technology. Although it has been around for a long time, it has not been until now, we also hope to bring a revolution to the web development industry, so that we can move towards the development of RIA (rich clients). Of course, there are also disadvantages to anything. if Javascript is used too much, therefore, the client will be very bloated, which is not conducive to the user's browsing experience. Therefore, it is necessary for Web developers to work together to achieve a good user experience while ensuring quick access.
the process of using asynchronous callback is a bit complicated, but the Ajax and information prompting functions are basically implemented. If many template information prompts are received, you can also set the layer to handle this problem. Template File: upload. TPL processes the uploaded PHP file: upload. this is the process in which PHP uses the POST method. Of course, the actual development situation may be more complex, which requires developers to think about it. When you click "News 1", the retrieved content is displayed at the corresponding layer below, and the page is not refreshed. Of course, the show. php file is omitted above. we just assume that the show. php file exists and can normally extract the news with ID 1 from the database.
News 1


you may say that this code calls the XMLHTTP component, is it possible only for IE browsers? I have tried it, but Firefox can also be used.
before executing any Ajax operation, we must call our initajax () function to instantiate an Ajax object.
url = "XXX. asp? "+ Math. Round (math. Random () * 100)
force refresh

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.