About Ajax caching in Javascript

Source: Internet
Author: User
Tags smarty template

AJAX cache is intended to improve AJAX efficiency and reduce the pressure on the server. However, improper use may lead to unexpected results. There are several solutions to disable Ajax caching:

1. Add the header ("Cache-Control: no-cache, must-revalidate") to the server (such as in php)
2. Add anyAjaxObj. setRequestHeader ("If-Modified-Since", "0") before ajax sends a request ");
3. Add anyAjaxObj. setRequestHeader ("Cache-Control", "no-cache") before ajax sends a request ");
4. Add "? Fresh = "+ Math. random (); // of course, the fresh parameter can be any one here
5. The fifth method is similar to the fourth method. Add "? Timestamp = "+ new Date (). getTime ();

6. Replace GET with POST: not recommended

Add a random number:
XmlHttp. open ("GET", "ajax. asp? Now = "+ new Date (). getTime (), true );

On the asp page to be obtained asynchronously, write a piece of code to prohibit caching:

Response. Buffer = True
Response. ExpiresAbsolute = Now ()-1
Response. Expires = 0
Response. CacheControl = "no-cache"

Add xmlHTTP. setRequestHeader ("If-Modified-Since", "0") before ajax sends a request.

XmlHTTP. open ("get", URL, true );
XmlHTTP. onreadystatechange = callHTML;
XmlHTTP. setRequestHeader ("If-Modified-Since", "0 ");
XmlHTTP. send ();

The AJAX cache is maintained by the browser. For a url sent to the server, ajax only interacts with the server during the first request. In subsequent requests, ajax no longer submits requests to the server, instead, extract data directly from the cache.

In some cases, we need to obtain the updated data from the server every time. The idea is to make the URLs of each request different without affecting the normal application: add random content after the url.

Url = url + "&" + Math. random ();

We all know that the main reason why ajax can speed up page loading is that it reduces the loading of duplicate data through ajax and truly achieves on-demand acquisition. In this case, when writing an ajax program, we may send it to the west and cache it again on the client side to further increase the data loading speed. That is, when loading data, the data is cached in the browser memory. Once the data is loaded, the data is always cached in the memory as long as the page is not refreshed, when you view the data again, you do not need to obtain the data from the server, which greatly reduces the server load and improves the user experience.

[AJAX application]
1. Initialize Ajax
Ajax actually calls the XMLHttpRequest object. First, we must call this object. We construct an Ajax initialization function:


Copy the code 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. Ajax uses the Get method
Now let's first execute a Get request. Do we need to Get/show. php? Id = 1 data, so what should we do?
Assume there is a link: <a href = "/show. php? Id = 1 "> News 1 </a>. When I click this link, I don't want to refresh it to see the link content. What should I do?
// Change the link:
// Set a layer for receiving news, and set it to not display:
At the same time, construct the corresponding JavaScript function:

Copy the code as follows:
Function getNews (newsID)
{
// If newsID is not passed in
If (typeof (newsID) = 'undefined ')
{
Return false;
}
// 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 ();
// Get Requests
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;
}
}
// 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 the code as follows:
// Construct a form. All attributes such as action and method are handled 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 the code 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 are not familiar with it, please read the relevant technical materials.
Upload File: upload.html

Copy the code as follows:
// Upload the 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 );
}

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.