开发者

Can't disable jQuery cache

Update

I figured out that it must be caching problem but I can't turn cache off. Here is my changed script:

<script src="../../Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
        jQuery.ajaxSetup({
            // Disable caching of AJAX responses 
            cache: false
        });

        jQuery("#button1").click(function (e) {
            window.setInterval(refreshResult, 3000);
        });

        function refreshResult()
        {
            jQuery("#divResult").load("/Home/Refresh");
        }
&l开发者_StackOverflowt;/script>

It updates part of a web page every 3 sec. It works only once after clearing web browser cache, after that it doesn't work - requests are made to /Home/Refresh without interval of 3 seconds, data is send from the server, but nothing is displayed on the web page; subsequent requests send cookie ASP.NET_SessionId=wrkx1avgvzwozcn1frsrb2yh. I am using ASP.NET MVC 2 and c#.

I have a problem with jQuery, here is how my web app works

  • Search.aspx web page which contains a form and jQuery script posts data to Search() action in Home controller after user clicks button1 button.

Search.aspx:

<%@ Page Title="" Language="C#" 
    MasterPageFile="~/Views/Shared/Site.Master" 
    Inherits="System.Web.Mvc.ViewPage<GLSChecker.Models.WebGLSQuery>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Title  
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <h2>Search</h2>

    <% Html.EnableClientValidation(); %>

    <% using (Html.BeginForm()) {%>    
        <fieldset>
            <div class="editor-label">
                <%: Html.LabelFor(model => model.Url) %>
            </div>
            <div class="editor-field">
                <%: Html.TextBoxFor(model => model.Url, 
                    new { size = "50" } ) %>
                <%: Html.ValidationMessageFor(model => model.Url) %>
            </div>

            <div class="editor-label">
                <%: Html.LabelFor(model => model.Location) %>
            </div>
            <div class="editor-field">
                <%: Html.TextBoxFor(model => model.Location, 
                    new { size = "50" } ) %>
                <%: Html.ValidationMessageFor(model => model.Location) %>
            </div>

            <div class="editor-label">
                <%: Html.LabelFor(model => model.KeywordLines) %>
            </div>
            <div class="editor-field">
                <%: Html.TextAreaFor(model => model.KeywordLines, 10, 60, null)%>  
                <%: Html.ValidationMessageFor(model => model.KeywordLines)%>
            </div>

            <p>
                <input id ="button1" type="submit" value="Search" />
            </p>
        </fieldset>

    <% } %>

    <script src="../../Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script type="text/javascript">
        jQuery("#button1").click(function (e) {
            window.setInterval(refreshResult, 5000);
        });

        function refreshResult()
        {
            jQuery("#divResult").load("/Home/Refresh");
        }
    </script>

   <div id="divResult"> 
   </div>

</asp:Content>
        [HttpPost]
        public ActionResult Search(WebGLSQuery queryToCreate)
        {
            if (!ModelState.IsValid)
                return View("Search");

            queryToCreate.Remote_Address = HttpContext.Request.ServerVariables["REMOTE_ADDR"];
            Session["Result"] = null;

            SearchKeywordLines(queryToCreate);

            Thread.Sleep(15000);

            return View("Search");
        }//Search()
  • After button1 button is clicked the above script from Search.aspx web page runs.

  • Search() action in controller runs for longer period of time. I simulate this in testing by putting Thread.Sleep(15000); in Search()action.

  • 5 sec. after Submit button was pressed, the above jQuery script calls Refresh() action in Home controller.

        public ActionResult Refresh()
        {               
            ViewData["Result"] = DateTime.Now;

            return PartialView();
        }
  • Refresh() renders this partial

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>

<%= ViewData["Result"] %>

The problem is that in Internet Explorer 8 there is only one request to /Home/Refresh; in Firefox 3.6.3 all requests to /Home/Refresh are made but nothing is displayed on the web page. Another problem with Firefox is that requests to /Home/Refresh are made every second not every 5 seconds.

I noticed that after I clear Firefox cache the script works well first time button1 is pressed, but after that it doesn't work.

I would be grateful for helpful suggestions.


This is a bit of an old question now. But I had an issue that I thought was related to caching, but turned out to be something else and I thought someone at some point might find it useful.

I had a set of routines that went something like this

  1. MAIN PAGE calls SUB PAGE via .load. SUB PAGE has table for data entry and hyperlinks for kicking off SQL PAGE to execute relevant sql

  2. Following data entry into SUB PAGE (via MAIN PAGE), click on hyperlink updates database using SQL PAGE and then refreshes MAIN PAGE div that contains SUB PAGE

Well ... for hours I kept inputting data, then clicking the relevant links only to find that the MAIN PAGE div sometimes refreshed, sometimes didn't. F5 always worked though. So I was pretty sure I had a cache problem. So I stopped using .load and started using .ajax, using the 'cache: false'. I could see that .ajax was now suitably randomising the get url, yet still my MAIN PAGE div was not refreshing. I was certain I had a caching problem ...

But I did not.

Using Google Chrome's development tools - I could see that sometime my jQuery routine was doing exactly what it was supposed to do, i.e.

a) Click SUB PAGE; execute SQL PAGE; refresh MAIN PAGE div

And sometimes things happened in this order ...

b) Click SUB PAGE; refresh MAIN PAGE div; execute SQL PAGE

My code was written to do a), but because SQL PAGE took a while to execute, b) was actually what was happening. And b) was bad - my MAIN PAGE div was actually refreshing, but the SQL to update my data tables was not executing prior to the refresh.

Once I realised this, the fix was easy. Using .ajax, I implemented the following logic:

i) Click SUB PAGE ii) Execute SQL PAGE iii) Conditional on the successful execution of the SQL PAGE (using the 'success:' option in .ajax), then refresh MAIN PAGE div containing SUB PAGE iv) I left the 'cache: false' in place, just in case

This fix works 100% of the time for my code

So if you are pulling your hair out trying to work out why caching won't turn off, just make sure that you actually have a caching problem and not the problem I have described above.

Good luck


You could change the URL you are requesting by adding a timestamp as part of the GET parameters:

function refreshResult()
{
  jQuery("#divResult").load("/Home/Refresh?"+(+new Date()));
}

This should ignore the browser cache (as the url is changing every time). Of course - this is what setting the jQuery cache parameter to false on ajax requests does, I'm just not 100% sure that .load() will use that setting.


Any browser ajax handling. Never cached.

// Global Vars
var ajaxRefreshCount = 0;
var ajaxRequestsCount = 0;

// Call this function for the ajax request
function ajaxRequest(name)
{
    ajaxRefreshCount++;
    ajaxRequestsCount++;
    var reqAjax = jQuery.get("/?ajax=" + name + "&r="+ajaxRefreshCount+"&s="+new Date().getTime(), function (data) { ajaxCallback(data, name)} );
}

function ajaxCallback(data, ajaxRequestName)
{
    ajaxRequestsCount--;

        // Your Stuff
        if (ajaxRequestName == "home_refresh")
            jQuery("#divResult").html(data);

    if (ajaxRequestsCount == 0) ajaxFullyLoaded();
}

function ajaxFullyLoaded()
{
    // Execute when all ajax requests where processed
}

// Example for home refresh
ajaxRequest("home_refresh");


The IE8 problem might be that IE caches similar requests, but I'm not too familiar with JQueries internals if they handle this or not, a solution could be to add a random get var.


I found the solution, I replaced

<% using (Html.BeginForm()) {%>

with

<% using (Ajax.BeginForm(null)) {%>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜