设置Ajax的cache:true能否节省带宽并规避谷歌地图API请求限额?
cache: true是否能避免重复发起谷歌地图Place Autocomplete请求? 问题背景
我不想超出谷歌地图会员的请求限额,且很多请求内容重复,无需重复发起。目前我使用的代码如下:
$.ajax({ type: "GET", headers: { "Content-Type": "application/json" }, cache: true, url: "https://maps.googleapis.com/maps/api/place/autocomplete/json?INPUT_AND_API_KEY_AND_SOME_OTHER_PARAMS", data: JSON.stringify(myData), success: function(response) { // 处理响应的代码 } });
请问仅设置cache: true是否足够?这里的“足够”指不会重复发起相同请求,从而节省带宽并将请求量控制在限额内。
回答
Great question—controlling API request limits is critical when working with paid services like Google Maps, so let’s break this down clearly:
Short answer: No, setting only cache: true isn’t reliable enough to guarantee you won’t send duplicate requests. Here’s why:
jQuery’s
cache: truedepends entirely on browser behavior
When you setcache: truefor a GET request, jQuery just tells the browser not to add a random_={timestamp}parameter to the URL (which it does by default for GET requests to bypass caching). But the actual caching decision is up to the browser—and the response headers sent by Google’s API.- If Google’s Place Autocomplete API returns headers like
Cache-Control: no-cacheormax-age=0, the browser will ignore any existing cache and send a fresh request every time, regardless of yourcache: truesetting. - Even if the API allows caching, browsers have limits on how much they’ll cache, and they might evict old cache entries without warning.
- If Google’s Place Autocomplete API returns headers like
Your request setup has a potential issue
You’re usingdata: JSON.stringify(myData)with a GET request. jQuery will append this string directly to the URL as a query parameter, which could create inconsistent URL formats (and thus miss cache hits) ifmyDatahas whitespace or special characters that aren’t properly encoded. For GET requests, it’s better to passmyDataas an object so jQuery can encode it correctly:data: myData, // instead of JSON.stringify(myData)To reliably avoid duplicate requests, implement your own local cache
The only way to guarantee you don’t send redundant requests is to handle caching yourself, before even firing the AJAX call. Here’s a simple example using an in-memory cache:// Create a global cache object to store autocomplete results const autocompleteCache = {}; function fetchAutocomplete(inputParams) { // Create a unique key for the request (based on all relevant parameters) const cacheKey = JSON.stringify(inputParams); // Check if we already have a cached result if (autocompleteCache[cacheKey]) { // Use the cached response instead of making a new request handleAutocompleteResponse(autocompleteCache[cacheKey]); return; } // No cache found—send the AJAX request $.ajax({ type: "GET", cache: true, // Still use browser cache as a fallback url: "https://maps.googleapis.com/maps/api/place/autocomplete/json", data: { input: inputParams.input, key: inputParams.apiKey, // Add all other required parameters here }, success: function(response) { // Store the response in our local cache autocompleteCache[cacheKey] = response; handleAutocompleteResponse(response); } }); } function handleAutocompleteResponse(response) { // Your existing response handling code goes here }- For longer-term caching, you could use
localStorageinstead of an in-memory object, but be sure to add a timestamp to each cache entry so you can expire old data (since place data can change over time). - This approach gives you full control over which requests are cached, and you won’t rely on unpredictable browser behavior.
- For longer-term caching, you could use
Final Takeaway
cache: true is a nice fallback, but it’s not a reliable solution for staying under API request limits. To be 100% sure you’re not sending duplicate requests, implement your own local caching logic。
内容的提问来源于stack exchange,提问作者Raz

