programing

jQuery .load 응답 캐시 중지

lastmemo 2023. 3. 7. 21:03
반응형

jQuery .load 응답 캐시 중지

URL에서 GET 요청을 하는 다음 코드가 있습니다.

$('#searchButton').click(function() {
    $('#inquiry').load('/portal/?f=searchBilling&pid=' + $('#query').val());            
});

그러나 반환된 결과가 항상 반영되는 것은 아닙니다.예를 들어 스택트레이스를 뱉는 응답을 변경했는데 검색 버튼을 클릭해도 스택트레이스가 표시되지 않습니다.Ajax 응답을 제어하는 기본 PHP 코드를 살펴보니 올바른 코드를 가지고 있었고 페이지를 직접 방문하여 올바른 결과를 보여주었지만 .load에 의해 반환된 출력은 오래되었습니다.

브라우저를 닫고 다시 열면 한 번 작동한 후 오래된 정보가 반환되기 시작합니다.이것을 jQuery로 제어할 수 있습니까, 아니면 캐시를 제어하기 위해 PHP 스크립트 출력 헤더를 사용할 필요가 있습니까?

보다 해야 합니다.$.ajax()★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★또는 모든 기능을 끄려면 스크립트 맨 위에 다음과 같이 입력합니다.

$.ajaxSetup ({
    // Disable caching of AJAX responses
    cache: false
});

다음으로 캐시를 요청 단위로 제어하는 예를 나타냅니다.

$.ajax({
    url: "/YourController",
    cache: false,
    dataType: "html",
    success: function(data) {
        $("#content").html(data);
    }
});

1가지 방법은 URL 끝에 원하는 번호를 추가하는 것입니다.

$('#inquiry').load('/portal/?f=searchBilling&pid=' + $('#query').val()+'&uid='+uniqueId());

호출할 때마다 다른 것을 반환하기 위해 uniqueId()를 입력합니다.

서버로부터 데이터를 취득할 필요가 있는 경우에만 아래 행을 입력하는 또 다른 접근법은 아래 행을 Ajax URL과 함께 추가합니다.

'?_='+Math.round(Math.random()*10000)

/**
 * Use this function as jQuery "load" to disable request caching in IE
 * Example: $('selector').loadWithoutCache('url', function(){ //success function callback... });
 **/
$.fn.loadWithoutCache = function (){
 var elem = $(this);
 var func = arguments[1];
 $.ajax({
     url: arguments[0],
     cache: false,
     dataType: "html",
     success: function(data, textStatus, XMLHttpRequest) {
   elem.html(data);
   if(func != undefined){
    func(data, textStatus, XMLHttpRequest);
   }
     }
 });
 return elem;
}

사샤가 좋은 생각이야, 난 믹스를 써

함수를 만듭니다.

LoadWithoutCache: function (url, source) {
    $.ajax({
        url: url,
        cache: false,
        dataType: "html",
        success: function (data) {
            $("#" + source).html(data);
            return false;
        }
    });
}

또, 예를 들면, init시에, 마이 페이지의 다른 부분을 호출합니다.

Init: 함수(actionUrl1, actionUrl2, actionUrl3) {

var의 예JS={

Init: function (actionUrl1, actionUrl2, actionUrl3)           ExampleJS.LoadWithoutCache(actionUrl1, "div1");

예 JSLoadWithoutCache(actionUrl2, "div2")의 예캐시 없이 JS.LoadWithoutCache(actionUrl3, "div3") ; }}.

이것은 IE에서 특히 귀찮은 부분입니다.기본적으로 서버의 응답과 함께 '캐시 없음' HTTP 헤더를 다시 보내야 합니다.

PHP의 경우 원하는 정보를 제공하는 스크립트에 다음 행을 추가합니다.

header("cache-control: no-cache");

또는 쿼리 문자열에 고유 변수를 추가합니다.

"/portal/?f=searchBilling&x=" + (new Date()).getTime()

Jquery의 .load() 메서드를 계속 사용하려면 JavaScript 타임스탬프처럼 URL에 고유한 내용을 추가합니다."+new Date().get Time()."pid 변수가 변경되지 않도록 "&time="을 추가해야 했습니다.

$('#searchButton').click(function() {
$('#inquiry').load('/portal/?f=searchBilling&pid=' + $('#query').val()+'&time='+new Date().getTime());            
});

방문하는 모든 페이지가 jquery mobile에 의해 DOM에 캐시되어 모바일의 메모리가 부족해지는 문제가 발생하므로 고유한 URL을 만들기 위해 타임스탬프를 사용하지 마십시오.

$jqm(document).bind('pagebeforeload', function(event, data) {
    var url = data.url;
    var savePageInDOM = true;

    if (url.toLowerCase().indexOf("vacancies") >= 0) {
        savePageInDOM = false;
    }

    $jqm.mobile.cache =  savePageInDOM;
})

이 코드는 페이지가 로드되기 전에 활성화됩니다.url.indexOf()를 사용하여 URL이 캐시 대상인지 여부를 판단하고 그에 따라 캐시 파라미터를 설정할 수 있습니다.

URL을 변경하려면 window.location = "을 사용하지 마십시오. 그렇지 않으면 주소로 이동하여 pagebeforeload가 실행되지 않습니다.이 문제를 해결하려면 window.location을 사용하십시오.해시 = " ,

jquery load 함수를 캐시가 false로 설정된 버전으로 바꿀 수 있습니다.

(function($) {
  var _load = jQuery.fn.load;
  $.fn.load = function(url, params, callback) {
  if ( typeof url !== "string" && _load ) {
        return _load.apply( this, arguments );
  }
    var selector, type, response,
      self = this,
      off = url.indexOf(" ");

    if (off > -1) {
      selector = stripAndCollapse(url.slice(off));
      url = url.slice(0, off);
    }

    // If it's a function
    if (jQuery.isFunction(params)) {

      // We assume that it's the callback
      callback = params;
      params = undefined;

      // Otherwise, build a param string
    } else if (params && typeof params === "object") {
      type = "POST";
    }

    // If we have elements to modify, make the request
    if (self.length > 0) {
      jQuery.ajax({
        url: url,

        // If "type" variable is undefined, then "GET" method will be used.
        // Make value of this field explicit since
        // user can override it through ajaxSetup method
        type: type || "GET",
        dataType: "html",
        cache: false,
        data: params
      }).done(function(responseText) {

        // Save response for use in complete callback
        response = arguments;

        self.html(selector ?

          // If a selector was specified, locate the right elements in a dummy div
          // Exclude scripts to avoid IE 'Permission Denied' errors
          jQuery("<div>").append(jQuery.parseHTML(responseText)).find(selector) :

          // Otherwise use the full result
          responseText);

        // If the request succeeds, this function gets "data", "status", "jqXHR"
        // but they are ignored because response was set above.
        // If it fails, this function gets "jqXHR", "status", "error"
      }).always(callback && function(jqXHR, status) {
        self.each(function() {
          callback.apply(this, response || [jqXHR.responseText, status, jqXHR]);
        });
      });
    }

    return this;
  }
})(jQuery);

jquery 로드 후 실행할 글로벌한 장소에 배치하면 모든 준비가 완료됩니다.기존 로드 코드는 더 이상 캐시되지 않습니다.

이것을 시험해 보세요.

$("#Search_Result").load("AJAX-Search.aspx?q=" + $("#q").val() + "&rnd=" + String((new Date()).getTime()).replace(/\D/gi, ''));

사용했을 때는 잘 작동했어요.

일부 서버(Apache2 등)가 캐시 허용 또는 거부하도록 설정되어 있지 않은 경우 HTTP 헤더를 "no-cache"로 설정해도 기본적으로 서버가 "캐시된" 응답을 보낼 수 있습니다.따라서 서버가 응답을 보내기 전에 어떤 것도 "캐시"하고 있지 않은지 확인합니다.

Apache2의 경우,

1) "disk_cache.conf" 파일 편집 - 캐시를 비활성화하려면 "CacheDisable /local_files" 지시문을 추가합니다.

2) mod_cache 모듈 로드(Ubuntu에서는 sudo a2enmod 캐시 및 sudo a2enmod disk_cache)

3) Apache2를 재부팅합니다(Ubuntu "sudo service apache2 restart").

이렇게 하면 서버 측에서 캐시를 비활성화할 수 있습니다.건배! :)

이 코드가 도움이 될 수 있습니다.

var sr = $("#Search Result");
sr.load("AJAX-Search.aspx?q=" + $("#q")
.val() + "&rnd=" + String((new Date).getTime())
.replace(/\D/gi, ""));

언급URL : https://stackoverflow.com/questions/168963/stop-jquery-load-response-from-being-cached

반응형