programing

브라우저가 AJAX 요청을 캐싱하지 않음

linuxpc 2023. 3. 22. 20:47
반응형

브라우저가 AJAX 요청을 캐싱하지 않음

Opera와 Firefox에서는 훌륭하게 동작하지만 Google Chrome에서는 AJAX 요청을 캐시하여 오래된 데이터를 제공합니다.

http://gapps.qk.com.au이 그 앱이다.Chrome에서 실행되면 AJAX 요청도 전송되지 않지만 다른 브라우저에서 실행하려고 하면 항상 AJAX 요청을 수행하고 데이터를 반환합니다.

Chrome의 동작을 막는 방법(Apache/PHP/HTML/JS)이 있습니까?

AJAX 콜:

function sendAjax(action,domain,idelement) {

                    //Create the variables
                var xmlhttp,
                    tmp,
                    params = "action=" + action
                             + "&domain=" + encodeURIComponent(domain)

                    xmlhttp = new XMLHttpRequest(); 
                //Check to see if AJAX request has been sent
                xmlhttp.onreadystatechange = function () {
                    if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
                        $('#'+idelement).html(xmlhttp.responseText);
                    }
                };
                xmlhttp.open("GET", "ajax.php?"+params, true);
                xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                //console.log(params);
                xmlhttp.send(params);

            }
sendAjax('gapps','example.com','gapps');

브라우저 캐시는 설정에 따라 다르게 동작합니다.사용자 설정이나 사용자의 브라우저에 의존하지 마십시오.브라우저가 헤더를 무시하도록 할 수도 있습니다.

캐시를 방지하는 방법은 두 가지가 있습니다.

--> AJAX 요구를 POST로 변경합니다.브라우저는 POST 요구를 캐시하지 않습니다.

--> Better Way & Good way : 현재 타임스탬프 또는 기타 원하는 번호를 사용하여 요청에 파라미터를 추가합니다.

params = "action=" + action 
         + "&domain=" + encodeURIComponent(domain) 
         + "&preventCache="+new Date();

Javascript 솔루션의 또 다른 대안은 커스텀헤더를 사용하는 것입니다.PHP에서는 다음과 같습니다.

<?php
   header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");//Dont cache
   header("Pragma: no-cache");//Dont cache
   header("Expires: Thu, 19 Nov 1981 08:52:00 GMT");//Make sure it expired in the past (this can be overkill)
?>

이 문제가 발생했을 때 jQuery ajax 요청을 사용하고 있었습니다.

jQuery API에 따르면 "cache: false"를 추가하면 승인된 답변에 설명된 것과 같은 타임스탬프가 추가됩니다.

이것은 GET 및 HEAD 요청에서만 작동하지만 POST를 사용하는 경우 브라우저는 Ajax 요청을 캐시하지 않습니다.가 있지만 IE8의 경우 필요에 따라 링크에서 확인하십시오.

$.ajax({ 
type: "GET",
cache: false, 
});

아래 코드 라인이 내게는

$.ajaxSetup({ cache: false });

언급URL : https://stackoverflow.com/questions/11463637/prevent-browser-from-caching-ajax-requests

반응형