简体   繁体   English

如何在浏览器中预取一个返回JSON格式数据的ajax调用

[英]How to prefetch an ajax call that returns a JSON format data in the browser

I have a use case wherein I am making multiple ajax calls when the page loads. 我有一个用例,其中在页面加载时我进行了多个ajax调用。 The initial load fires off an ajax request to the server that gets the data in JSON format, upon subsequent user clicks other ajax calls are fired that make database calls to compute the JSON on the server side , the browser typically is idle and waits for the JSON to be returned. 初始负载向服务器发送ajax请求,该请求以JSON格式获取数据,随后的用户单击时,将触发其他ajax调用,这些调用使数据库调用在服务器端计算JSON,浏览器通常处于空闲状态并等待要返回的JSON。 I was thinking of some ways in which I might be able to speed up the execution of this from the application side. 我正在考虑一些方法,可以从应用程序方面加快执行速度。

Is there a way in Jquery to fire off the subsequent ajax request before hand and save it somewhere on the client , so that when a user click happen the page the JSON gets parsed from the cache and rendered in the DOM instead of the delayed request to the server. Jquery中是否有一种方法可以预先触发后续的Ajax请求并将其保存在客户端上的某个位置,以便在用户单击该页面时,JSON从缓存中解析并呈现在DOM中,而不是延迟请求传递到服务器。

jQuery AJAX requests are being cached by the browser (assuming it is a GET request, POST will always hit the server). jQuery AJAX请求被浏览器缓存(假设它是GET请求,则POST总是会到达服务器)。 So if you can predict the calls most likely to happen, you can spin off a function during initialization to make these calls preemptively, and you should get the results for the subsequent calls from the browser cache. 因此,如果您可以预测最有可能发生的调用,则可以在初始化期间派生一个函数来抢先进行这些调用,并且应该从浏览器缓存中获取后续调用的结果。 Make sure the server actually sends appropriate cache headers, though. 但是,请确保服务器实际发送了适当的缓存头。

Another option would be to wrap the call to the jQuery AJAX function in a function of your own and hold the data in an array in memory. 另一个选择是将对jQuery AJAX函数的调用包装到您自己的函数中,并将数据保存在内存中的数组中。 In this case, make sure you have a way of aging out old results at some point, or you will fill up the browsers memory. 在这种情况下,请确保您有某种方式可以老化旧的结果,否则您将填满浏览器的内存。

What you can do is fire off all the AJAX requests when you load the page, and assign them to promise variables. 您可以做的是在加载页面时触发所有AJAX请求,并将它们分配给Promise变量。 When you need to use the result, use $.when() 当您需要使用结果时,请使用$.when()

var ajax1 = $.ajax( { ... } );
...
$.when(ajax1).then(function(response) {
    // Do what you need
});

You can 您可以

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM