Ajax clears cache instances

Source: Internet
Author: User
Tags add time

The benefits of Ajax are Needless to say, such as asynchronous loading, partial refreshing, and user experience improvement.

A problem occurs when Ajax is used for data submission. After each submission, the last update prompt is always displayed.

After manual cleaning of the browser cache, it seems that the problem can be solved. However, after one submission, the second issue is the same.

Next, let's take a look at what I made.Program

I made a small online voting program and used ajax to submit the voting data of the foreground to the background database.

The problem requirements are described as follows:The program requires proper judgment and prompt, if the same IP address can only be restricted to one vote within the same day;

If it is submitted for the first time, "Vote successful" is displayed. If the IP address already exists in the same topic cannot be voted again, "No Repeated voting" is displayed ".

After the problem is described, it seems very simple.

The JS script submitted by the front-end HTML is as follows:

Function submitvote (OBJ) {var Eve = getevent (); var CHR = document. getelementsbyname ("netvote"); var COUNT = 0; var sellist = ""; for (VAR I = 0; I <Chr. length; I ++) {If (CHR [I]. checked) {count ++; sellist + = CHR [I]. value + "," ;}}if (count <1) {alert ("not selected"); If (Eve. preventdefault) {Eve. preventdefault ();} else {Eve. returnvalue = false;} return false;} var posturl = "/ashx/vote. ashx? Id = "+ OBJ +" & optionid = "+ sellist request. sendget (posturl, cackbackresult, null, null);} function cackbackresult (req) {var STR = req. responsetext; If (STR = "0") // if no option is selected {alert ("not selected"); Return false;} If (STR = "001 ") // {alert ("repeated votes cannot be made") that has been cast; return false;} If (STR = "002 ") {alert ("Vote successful"); location.href}'ulult.html ';}} background processing Code : Public void processrequest (httpcontext context) {context. response. contenttype = "text/plain"; int qid = gain. getqueryint ("ID", 0); // question No. String optionid = gain. getquerystring ("optionid"); If (string. isnullorempty (optionid) {context. response. write ("0"); // no option} else if (qid> 0) {try {eey. lib. bll. voteip bvip = new eey. lib. bll. voteip (); string IP = gain. getuserip; string strwhere = string. form At ("IP = '{0}' and optionid = {1} And datediff (D, votetime, getdate () <1", IP, qid); If (bvip. exists (strwhere) {context. response. write ("001"); // the same IP address can only vote for one problem once a day} else {int optid = 0; string [] arry = NULL; If (optionid. indexof (',')> = 0) {optionid = optionid. trimend (','); If (optionid. indexof (',')> = 0) // multiple options {arry = optionid. split (',');} else {arry = new string [1] {optionid };}} eey. lib. mo Del. voteip vmodel = new eey. lib. model. voteip (); vmodel. IP = IP; vmodel. optionid = qid; vmodel. votetime = datetime. now; bvip. add (vmodel); If (! Arry. equals (null) {eey. lib. bll. option bopt = new eey. lib. bll. option (); For (INT I = 0; I <Arry. length; I ++) {optid = strutil. toint32 (arry [I], 0); bopt. updatecount (optid);} int Total = bopt. getquestionvote (qid); eey. lib. bll. question BQ = new eey. lib. bll. question (); If (Bq. updatevote (qid, total)> 0) {context. response. write ("002"); // added successfully }}} catch (system. exception ex) {context. response. write (ex. message );}}}

Tests show that the same IP address can only be voted once when the vote is submitted, that is, you can check the database ticket count records (the number of votes is updated after the first submission, but the number of votes has not changed since the first submission ).

Every time you click to vote at the front-end, a prompt is displayed."Vote successful"In fact, there is no update record.

Obviously it is not the result we want. Therefore, it can be determined that it is definitely an Ajax cache problem. If there is a cache, it will not execute background code every time. Therefore, it can be determined that the problem is submitted by the front-end, and the results are submitted in a timely manner instead of the previous cached results.
Solution:
Add the time limit when submitting

That is, modify the posturl:

VaR posturl = "/ashx/vote. ashx? Id = "+ OBJ +" & optionid = "+ sellist +" & guid = "+ new date (). gettime ();

// + "& Guid =" + new date (). gettime ();

After this time, the problem is solved. Obviously, Ajax returns the background processing result in real time, which is achieved by our goal. OK

 

Summary

There are three methods for Ajax to solve the cache.

1. Add Time Limit
For a browser, your first click will call the RPC request, but when you use the same browser to submit a form, RPC will not be submitted because the parameters are the same, this may be a problem with the XMLHTTPRequest object of Ajax. For example, if the time interval is set, it is actually (New activexobject ("Microsoft. XMLHTTP ") So, in actual operations, pass a useless guid = new date () to the RPC parameter (). gettime ()
A timestamp to ensure that each click event will trigger the RPC request because such parameters (or URLs) are different.
Why do we need to append the timestamp to the target URL?
In some cases, Some browsers cache the results of multiple XMLHttpRequest requests in the same URL. If the response to each request is different, this will bring bad results. Append the current timestamp to the end of the URL to ensure the uniqueness of the URL, thus avoiding the browser's cache results.

2. Write a piece of code to prohibit caching on the page to be obtained asynchronously:
Response. Buffer = true
Response. expiresabsolute = now ()-1
Response. expires = 0
Response. cachecontrol = "no-Cache"

3. Add XMLHTTP. setRequestHeader ("If-modified-since", "0") before Ajax sends a request. cache can be disabled.
XMLHTTP. Open ("get", URL, true );
XMLHTTP. onreadystatechange = callhtml;
XMLHTTP. setRequestHeader ("If-modified-since", "0 ");
XMLHTTP. Send ();

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.