IT박스

IE8에서 예기치 않은 AJAX 캐싱 결과

itboxs 2020. 6. 25. 22:02
반응형

IE8에서 예기치 않은 AJAX 캐싱 결과


JQuery Ajax 요청의 Internet Explorer 캐싱 결과에 심각한 문제가 있습니다.

웹 페이지에 사용자가 새 페이지를 탐색 할 때마다 업데이트되는 헤더가 있습니다. 페이지가로드되면이 작업을 수행합니다

$.get("/game/getpuzzleinfo", null, function(data, status) {
    var content = "<h1>Wikipedia Maze</h1>";
    content += "<p class='endtopic'>Looking for <span><a title='Opens the topic you are looking for in a separate tab or window' href='" + data.EndTopicUrl + "' target='_blank'>" + data.EndTopic + "<a/></span></p>";
    content += "<p class='step'>Step <span>" + data.StepCount + "</span></p>";
    content += "<p class='level'>Level <span>" + data.PuzzleLevel.toString() + "</span></p>";
    content += "<p class='startover'><a href='/game/start/" + data.PuzzleId.toString() + "'>Start Over</a></p>";

    $("#wikiheader").append(content);

}, "json");

그냥 헤더 정보를 페이지에 삽입합니다. www.wikipediamaze.com 으로 이동 한 다음 로그인하여 새 퍼즐을 시작하여 확인할 수 있습니다 .

테스트 한 모든 브라우저 (Chrome, Firefox, Safari, Internet Explorer) 에서 IE를 제외하고 는 훌륭하게 작동합니다 . Eveything은 처음으로 IE에 제대로 주입 되었지만 그 후에는 결코 호출하지 않습니다 /game/getpuzzleinfo. 결과 또는 무언가를 캐시 한 것과 같습니다.

$.post("/game/getpuzzleinfo", ...IE로 전화를 바꾸면 전화가 잘 걸립니다. 그러나 Firefox는 작동을 멈 춥니 다.

IE가 왜 내 $.get아약스 호출을 캐싱하는지에 대해 누군가가 이것에 대해 약간의 조명을 줄 수 있습니까 ?

최신 정보

아래 제안에 따라 내 아약스 요청을 이것으로 변경하여 문제를 해결했습니다.

$.ajax({
    type: "GET",
    url: "/game/getpuzzleinfo",
    dataType: "json",
    cache: false,
    success: function(data) { ... }
});

IE는 Ajax 응답을 적극적으로 캐싱하는 것으로 유명합니다. jQuery를 사용하면서 전역 옵션을 설정할 수 있습니다.

$.ajaxSetup({
    cache: false
});

jQuery가 요청 쿼리 문자열에 임의의 값을 추가하여 IE가 응답을 캐싱하지 못하게합니다.

캐싱을 원하는 곳에서 다른 Ajax 호출이 진행중인 경우 해당 호출도 비활성화됩니다. 이 경우 $ .ajax () 메소드 사용으로 전환하고 필요한 요청에 대해 해당 옵션을 명시 적으로 활성화하십시오.

자세한 정보는 http://docs.jquery.com/Ajax/jQuery.ajaxSetup참조 하십시오 .


으로 marr75는 언급 GET의가 캐시됩니다.

이를 방지하기위한 몇 가지 방법이 있습니다. 응답 헤더를 수정하는 것 외에도 무작위로 생성 된 쿼리 문자열 변수를 대상 URL의 끝에 추가 할 수도 있습니다. 이런 식으로 IE는 요청 될 때마다 다른 URL이라고 생각합니다.

이를 수행하는 방법에는 여러 가지가 있습니다 (예 : Math.random(), 날짜의 변형 등).

당신이 그것을 할 수있는 한 가지 방법이 있습니다 :

var oDate = new Date();
var sURL = "/game/getpuzzleinfo?randomSeed=" + oDate.getMilliseconds();
$.get(sURL, null, function(data, status) {
    // your work
});

가져 오기는 항상 캐시 가능합니다. 작동 할 수있는 한 가지 전략은 응답 헤더를 편집하고 클라이언트에게 정보를 캐시하지 않거나 캐시를 곧 만료하도록 지시하는 것입니다.


ashx 페이지를 호출하는 경우 다음 코드를 사용하여 서버에서 캐싱을 비활성화 할 수도 있습니다.

context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches); 

이것이 내가 아약스 호출을 위해하는 일입니다.

var url = "/mypage.aspx";
// my other vars i want to add go here
url = url + "&sid=" + Math.random();
// make ajax call

그것은 나를 위해 아주 잘 작동합니다.


NickFitz는 좋은 답변을 제공하지만 IE9에서도 캐싱을 해제해야합니다. IE8 및 IE9 만 대상으로하기 위해이 작업을 수행 할 수 있습니다.

<!--[if lte IE 9]>
<script>
    $.ajaxSetup({
        cache: false
    });
</script>
<![endif]-->

여기에 대한 답변은 jQuery를 사용하거나 어떤 이유로 든 xmlHttpRequest 객체를 직접 사용하는 사람들에게 매우 유용합니다 ...

자동 생성 된 Microsoft 서비스 프록시를 사용하는 경우 해결하기가 쉽지 않습니다.

요령은 이벤트 핸들러에서 Sys.Net.WebRequestManager.add_invokingRequest 메소드를 사용하여 요청 URL을 변경하는 것입니다.

networkRequestEventArgs._webRequest._url = networkRequestEventArgs._webRequest._url + '&nocache=' + new Date().getMilliseconds(); 

나는 이것에 대해 블로그에 올렸다 : http://yoavniran.wordpress.com/2010/04/27/ie-caching-ajax-results-how-to-fix/


ExtJS를 사용 하여이 정확한 문제에 대한 블로그를 작성했습니다 ( http://thecodeabode.blogspot.com/2010/10/cache-busting-ajax-requests-in-ie.html )

The problem was as I was using a specific url rewriting format I couldn't use conventional query string params (?param=value), so I had write the cache busting parameter as a posted variable instead..... I would have thought that using POST variables are a bit safer that GET, simply because a lot of MVC frameworks use the pattern

protocol://host/controller/action/param1/param2

and so the mapping of variable name to value is lost, and params are simply stacked... so when using a GET cache buster parameter

i.e. protocol://host/controller/action/param1/param2/no_cache122300201

no_cache122300201 can be mistaken for a $param3 parameter which could have a default value

i.e.

public function action($param1, $param2, $param3 = "default value") { //..// }

no chance of that happening with POSTED cache busters


If you are using ASP.NET MVC, it is enough to add this line on top of the controller action:

[OutputCache(NoStore=true, Duration = 0, VaryByParam = "None")]
public ActionResult getSomething()
{

}

IE is within its rights to do this caching; to ensure the item isn't cached, the headers should be set accordingly.

If you are using ASP.NET MVC, you can write an ActionFilter; in OnResultExecuted, check filterContext.HttpContext.Request.IsAjaxRequest(). If so, set the response's expire header: filterContext.HttpContext.Response.Expires = -1;

As per http://www.dashbay.com/2011/05/internet-explorer-caches-ajax/:

Some people prefer to use the Cache - Control: no - cache header instead of expires. Here’s the difference:
Cache-Control:no-cache – absolutely NO caching
Expires:-1 – the browser “usually” contacts the Web server for updates to that page via a conditional If-Modified-Since request. However, the page remains in the disk cache and is used in appropriate situations without contacting the remote Web server, such as when the BACK and FORWARD buttons are used to access the navigation history or when the browser is in offline mode.

참고URL : https://stackoverflow.com/questions/1013637/unexpected-caching-of-ajax-results-in-ie8

반응형