我正在使用 XHR GET 获取 Blade html 并尝试缓存它,这样它就不需要每次都去服务器下载它。这是我的代码。
但这不起作用并且总是转到服务器。
$.ajax({
method: "GET",
url: "{!! route('SendMessageForm') !!}",
cache: true,
async: true,
beforeSend: function(xhr, opts) {
$('#MessageModal').html(processingImageUrl);
},
success: function(result) {
$('#MessageModal').html(result);
PopulateActiveUsers();
},
error: function() {
}
});
Controller
public function SendMessageForm() {
return View("Chat.SendMessage");
}
标题信息
最佳答案
这实际上不是 jQuery 的错。根据文档:
Setting
cache
tofalse
will only work correctly with HEAD and GET requests. It works by appending"_={timestamp}"
to the GET parameters.
因此,它实际上通过更改 URL 来欺骗浏览器,强制浏览器加载所请求资源的新副本。所以浏览器认为这是一个新的请求,然后再次从服务器加载它。它并不实际上将响应缓存在某处。
缓存响应是浏览器的一部分,为了发挥这个作用,它需要适当的缓存 header 。我可以看到,您的回复不包含 @elegisandi 在评论中指出的适当 header 。因此这个问题有两种可能的解决方案。
向服务器响应添加缓存 header
您必须修改响应 header ,以便浏览器可以缓存响应。 This question它的答案可以帮助您进行设置。
手动缓存响应
您可以手动将请求的响应缓存在 JavaScript 对象中。 但请注意,您必须手动使这些过期。以下是如何执行此操作的示例:
var cache = {};
function ajaxCall(options) {
if (!cache[options.url]) {
cache[options.url] = $.ajax(options);
}
return cache[options.url];
}
// In your code
ajaxCall({
method: "GET",
url: "{!! route('SendMessageForm') !!}",
beforeSend: function (xhr, opts) {
$('#MessageModal').html(processingImageUrl);
}
})
.then(function (result) {
$('#MessageModal').html(result);
PopulateActiveUsers();
});
第二次向同一 URL 发出请求时,它实际上会从缓存中返回响应。此外,我们可以自定义ajaxCall
函数,以便它也检查请求方法。
关于jquery - XHR 中的缓存不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45406231/