Programing

jQuery .load 응답이 캐시되지 않도록 중지

lottogame 2020. 4. 10. 08:04
반응형

jQuery .load 응답이 캐시되지 않도록 중지


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

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

그러나 반환 된 결과가 항상 반영되는 것은 아닙니다. 예를 들어 스택 추적을 뱉어내는 응답을 변경했지만 검색 버튼을 클릭했을 때 스택 추적이 나타나지 않았습니다. 나는 아약스 응답을 제어하는 ​​기본 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);
    }
});

한 가지 방법은 URL 끝에 고유 번호를 추가하는 것입니다.

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

호출 할 때마다 다른 것을 반환하기 위해 uniqueId ()를 작성하는 경우


서버에서 데이터를 가져와야 할 때만 아래 줄을 넣는 또 다른 방법은 아약스 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;
}

Sasha는 좋은 생각입니다, 나는 혼합을 사용합니다.

함수를 만듭니다

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

그리고 init와 같이 내 페이지의 다른 부분을 호출하십시오.

초기화 : 함수 (actionUrl1, actionUrl2, actionUrl3) {

var ExampleJS = {

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

예 : JS.LoadWithoutCache (actionUrl2, "div2"); 예 : JS.LoadWithoutCache (actionUrl3, "div3"); }},


이것은 IE의 특별한 성가심입니다. 기본적으로 서버의 응답과 함께 'no-cache'HTTP 헤더를 다시 보내야합니다.


PHP의 경우 원하는 정보를 제공하는이 줄을 스크립트에 추가하십시오.

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

또는 쿼리 문자열에 고유 변수를 추가하십시오.

"/portal/?f=searchBilling&x=" + (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 = ""을 사용하지 마십시오. 그렇지 않으면 URL을 변경하기 위해 주소로 이동하면 pagebeforeload가 실행되지 않습니다. 이 문제를 해결하려면 window.location.hash = "";


jquery로드 기능을 캐시가 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 헤더를 "캐시 없음"으로 설정하더라도 서버는 기본적으로 "캐시 된"응답을 보낼 수 있습니다. 따라서 서버가 응답을 보내기 전에 어떤 것도 "캐싱"하지 않아야합니다.

Apache2의 경우

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

2) mod_cache 모듈로드 (Ubuntu "sudo a2enmod cache"및 "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, ""));

Jquery의 .load () 메소드를 고수하려면 JavaScript 타임 스탬프와 같이 URL에 고유 한 것을 추가하십시오. "+ 새 날짜 () .getTime ()". pid 변수를 변경하지 않도록 "& time ="을 추가해야합니다.

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

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

반응형