Ajax請求被緩存的幾種處理方式
我們都知道IE會針對ajax請求的地址緩存請求結果,直到緩存過期之前,針對相同地址發出的請求,只有第一次會請求會真正發送到服務端.在某種情況下,這種緩存機制確實能提高web的響應速度,但是有時候並不是我們需要的,有時候我們需要獲取即時信息,那么有哪幾種方式來解決這個問題呢,下面列舉了幾種解決方案!
1. 通過URL添加后綴的方式
這種方式是我們大家都會使用的技巧,大多人都知道
例如:
本來請求的地址是: /home/action?
加查詢參數后綴后:/home/action?ran=Match.Random();
后綴查詢參數變量可以自定義,只需要每次都變化即可!
2. 通過Jquery的Ajax API設置相關屬性(代碼中標紅處)
<script type="text/javascript">
var LoadTime = function () {$.ajaxSetup({ cache: false });
$.ajax({url: '@Url.Action("currTime")',
success: function (result) {
$("#currTime").html(result);
}})}</script>
我們使用fiddler抓取url請求,會發現此種方式與第一種解決方案類似,也是添加后綴的方式,如圖:
3. 通過定制響應(此處參考http://www.cnblogs.com/artech/archive/2013/01/03/cache-4-ie.html)
我們都知道http請求頭重包請求的相關屬性,此種方式通過控制消息頭中的Cache-Control包頭,並將其設置為”No-Cache”,這樣只是瀏覽器不對結果緩存.
那么如何達到上述目的呢?
首先,我們定義一個名為NoCacheAttribute的ActionFilter.在實現的OnActionExecuted方法中,我們調用當前HttpResponse的SetCacheability方法將緩存選項設置為NoCache.將該屬性應用到方法.然后運行我們的程序
先看NoCacheAttribute的定義:
public class NoCacheAttribute:FilterAttribute,IActionFilter{public void OnActionExecuted(ActionExecutedContext filterContext){filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);}public void OnActionExecuting(ActionExecutingContext filterContext){//throw new NotImplementedException();
}}將屬性應用到方法
[NoCache]public string CurrTime() {return DateTime.Now.ToLongTimeString();
}
</div>
<div class="postDesc">posted @ <span id="post-date">2013-07-28 16:31</span> <a href="https://www.cnblogs.com/jwly/">竹影木風</a> 閱讀(<span id="post_view_count">4912</span>) 評論(<span id="post_comment_count">0</span>) <a href="https://i.cnblogs.com/EditPosts.aspx?postid=3221251" rel="nofollow">編輯</a> <a href="#" onclick="AddToWz(3221251);return false;">收藏</a></div>
</div>
<script type="text/javascript">var allowComments=true,cb_blogId=67195,cb_entryId=3221251,cb_blogApp=currentBlogApp,cb_blogUserGuid='a15b1d3d-6526-df11-ba8f-001cf0cd104b',cb_entryCreatedDate='2013/7/28 16:31:00';loadViewCount(cb_entryId);var cb_postType=1;</script>