- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我的JS应用应该做什么的快速描述...
我在项目中使用JavaScript Promise库RSVP.js-https://github.com/tildeio/rsvp.js/。
代码可以执行的一些操作...
在第一个请求上使用AJAX加载4-5个JOSN URL,所有后续请求将改为从缓存的变量提供JSON。
JavaScript Promise()用于在执行应用程序中的其他代码之前加载所有JSON数据。
全局变量window.jsonCache会在第一次使用AJAX请求将缓存的JSON和Promise()首次加载到缓存中后,将保存它们。
getJSON(jsonUrl,key)是一个函数,它返回Promise()并发出AJAX请求或提供缓存的window.jsonCache [key-name-here]数据(如果有)。
目标是使用JavaScript's Promise()
并缓存从每个AJAX请求返回的JSON数据,并在对数据的任何重复调用中提供缓存的版本,而不是每次页面上的脚本调用数据时都重复进行AJAX请求。
我已经开始使用我的JavaScript知识来进行演示,而我仍然每天都在学习新的JS。我在PHP中更强大,但在JS中却不断进步。
我需要帮助/帮助的问题
我相信我的工作大部分都能满足我的需求。我的问题出在我的JSFiddle演示http://jsfiddle.net/jasondavis/nzzh1hee/5/上,该示例运行下面说明的所有代码。该演示使用对所有4个JSON URL的AJAX请求加载我的JSON数据。然后,它应缓存结果以供将来调用此数据。相反,下一次我调用/运行代码时,将重复进行AJAX调用。
因此,在某个地方,我的缓存机制似乎无法正常工作,甚至可能出现其他问题。
无论从AJAX请求还是从缓存的变量提供JSON数据,最终结果都应运行我的Promise()
代码。
我需要帮助以使这部分工作正常进行。上面的JSFiddle具有此代码的工作演示,您可以查看Dev工具控制台以查看我的调试数据。
更新
SO用户Kevin B确定了我的问题根源是在我的第一个调用有时间缓存值之前调用了对数据的第二个调用,这就是为什么要重复进行AJAX调用!
我可以使用一些帮助来修改此现有代码来解决此问题,如用户Jared Smith所述,如果我可以记住AJAX函数getJSON(jsonUrl,key)会是一个好方法,但我基本上是这样做的所以我可以在这里使用一些帮助!
边注...
JSFiddle演示使用/echo/json/
作为所有AJAX请求的端点,该请求在演示中不返回任何数据。因此,我还测试了从AJAX请求本地加载真实JSON数据的过程,只是为了确保这不是问题的根源,并且没有造成任何影响。
此行下的所有代码和文本都只是我的代码的细分,可以更好地解释。上面的文本足以理解问题和目标,并且JSFiddle演示运行以下代码
因此,我将在下面简要尝试分解我的演示代码,以解释其中的一些关键部分...
JSONCache将在成功加载AJAX后保存缓存的JSON数据,以供将来从此缓存中调用JSON数据的调用,而不是发出新的AJAX请求。
// Global variable to hold cached JSON data retrieved from AJAX requests
window.jsonCache = {
users: '',
milestones: '',
tags: '',
task: ''
};
if(isEmpty(window.jsonCache[key])) { }
发出AJAX请求。
handler()
回调函数,而该函数又会调用
Promise() resolve(this.response) function
将JSON数据传递到resolve函数。如果AJAX失败,它将调用
Promise() Reject() function
。
}else{
语句中,它将通过使用其
key
值对其进行访问而仅返回数据的缓存版本,并且不会对此数据/ url的特定
key
进行重复的AJAX请求。
// RSVP.js Promise Library used from https://github.com/tildeio/rsvp.js/
// utility function to check for empty variables
function isEmpty(str) {
return (!str || 0 === str.length || str === '');
}
// Global variable to hold cached JSON data retrieved from AJAX requests
window.jsonCache = {
users: '',
milestones: '',
tags: '',
task: ''
};
// AJAX function to load JSON data using Promise()
var getJSON = function(url, key) {
var promise = new RSVP.Promise(function(resolve, reject){
// If cached data is not set then make AJAX requiest to get it
if(isEmpty(window.jsonCache[key])) {
var client = new XMLHttpRequest();
client.open("GET", url);
client.onreadystatechange = handler;
client.responseType = "json";
client.setRequestHeader("Accept", "application/json");
client.send();
console.log('---- "client" XMLHttpRequest/AJAX variable ======= ',client);
////////////// temp test
// jsonCache[key] = ' AJAX Response';
////////////// end temp test
function handler() {
if (this.readyState === this.DONE) {
// On AJAX success, resolve() our Promise() and set result to cached variable
// to avoid duplicate AJAX requests for this jsonCache[key] Data where "key"
// is used to assign to each AJAX endpoint URL/request of JSON data...
// (milestones, tasks, users, etc...)
if (this.status === 200) {
window.jsonCache[key] = this.response;
window.jsonCache[key] = key+' AJAX Response';
console.log('---- window.jsonCache['+key+'] ====== ',window.jsonCache[key]);
// Resolve() the Promise() on AJAX success
resolve(this.response);
// On AJAX failure, reject() our Promise()
}else{
reject(this);
}
}
};
// If JSON data for this key is already cached, then return the cached version
// instead of making a new AJAX request!
}else{
console.log('---- window.jsonCache['+key+'] ====== ',window.jsonCache[key]);
// Return cached version of JSON data as a Promise() and pass into the
// Resolve() function
window.jsonCache[key] = key+' CACHED Response';
resolve(window.jsonCache[key]);
}
});
return promise;
};
// EXAMPLE USAGE DEMO
// usage loading multiple AJAX calls using Promises
// Each of these 4 JSON URLs below will be loaded using Promise() and AJAX requests on
// first call to them. 2nd call to them should instead serve a cached version stored in
// a global variable window.jsonCache.KEYNAME-HERE
var promises = {
users: getJSON('/echo/json/', 'users'),
milestones: getJSON('/echo/json/', 'milestones'),
tags: getJSON('/echo/json/', 'tags'),
task: getJSON('/echo/json/', 'task')
};
// Load the AJAX JSON function above for each Promise()
// Handles success, finally() for every load, and error for when error occurs
RSVP.hash(promises).then(function(results) {
console.log(results);
console.log(results.users); // print the users JSON results
}).finally(function(){
console.log('finally() function ran on success and failure.... It is always ran!');
}).catch(function(reason){
console.log('[ERROR] REASON:',reason.statusText); //if any of the promises fails.
});
/////////////////////////////////////////////////////////////////////////////////////////////////
//
//
// Below is another call to load the same 4 JSON data to test and see if it is
// served from a cached variable instead of making a duplicate 2nd AJAX request for each item.
//
//
////////////////////////////////////////////////////////////////////////////////////////////////
// EXAMPLE USAGE DEMO
// usage loading multiple AJAX calls using Promises
// Each of these 4 JSON URLs below will be loaded using Promise() and AJAX requests on
// first call to them. 2nd call to them should instead serve a cached version stored in
// a global variable window.jsonCache.KEYNAME-HERE
var promises = {
users: getJSON('/echo/json/', 'users'),
milestones: getJSON('/echo/json/', 'milestones'),
tags: getJSON('/echo/json/', 'tags'),
task: getJSON('/echo/json/', 'task')
};
// Load the AJAX JSON function above for each Promise()
// Handles success, finally() for every load, and error for when error occurs
RSVP.hash(promises).then(function(results) {
console.log(results);
console.log(results.users); // print the users JSON results
}).finally(function(){
console.log('finally() function ran on success and failure.... It is always ran!');
}).catch(function(reason){
console.log('[ERROR] REASON:',reason.statusText); //if any of the promises fails.
});
最佳答案
第二组请求在第一组请求完成之前发送,因此在缓存具有值之前,它们也将发送请求。您应将诺言存储在缓存中,并始终返回诺言。
这是一个简化的示例,该示例使用组合的sendRequest
方法返回诺言。
var cache = {};
function getData (url, key) {
if (!cache[key]) {
cache[key] = sendRequest(url);
}
return cache[key];
}
var promisesOne = {
users: getData('/echo/json/', 'users'),
milestones: getData('/echo/json/', 'milestones'),
tags: getData('/echo/json/', 'tags'),
task: getData('/echo/json/', 'task')
};
var promisesTwo = {
users: getData('/echo/json/', 'users'),
milestones: getData('/echo/json/', 'milestones'),
tags: getData('/echo/json/', 'tags'),
task: getData('/echo/json/', 'task')
};
关于javascript - JavaScript Promise Library在首次调用时使用AJAX请求加载JSON数据,然后在重复调用时从缓存的变量加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33288229/
我在网上搜索但没有找到任何合适的文章解释如何使用 javascript 使用 WCF 服务,尤其是 WebScriptEndpoint。 任何人都可以对此给出任何指导吗? 谢谢 最佳答案 这是一篇关于
我正在编写一个将运行 Linux 命令的 C 程序,例如: cat/etc/passwd | grep 列表 |剪切-c 1-5 我没有任何结果 *这里 parent 等待第一个 child (chi
所以我正在尝试处理文件上传,然后将该文件作为二进制文件存储到数据库中。在我存储它之后,我尝试在给定的 URL 上提供文件。我似乎找不到适合这里的方法。我需要使用数据库,因为我使用 Google 应用引
我正在尝试制作一个宏,将下面的公式添加到单元格中,然后将其拖到整个列中并在 H 列中复制相同的公式 我想在 F 和 H 列中输入公式的数据 Range("F1").formula = "=IF(ISE
问题类似于this one ,但我想使用 OperatorPrecedenceParser 解析带有函数应用程序的表达式在 FParsec . 这是我的 AST: type Expression =
我想通过使用 sequelize 和 node.js 将这个查询更改为代码取决于在哪里 select COUNT(gender) as genderCount from customers where
我正在使用GNU bash,版本5.0.3(1)-发行版(x86_64-pc-linux-gnu),我想知道为什么简单的赋值语句会出现语法错误: #/bin/bash var1=/tmp
这里,为什么我的代码在 IE 中不起作用。我的代码适用于所有浏览器。没有问题。但是当我在 IE 上运行我的项目时,它发现错误。 而且我的 jquery 类和 insertadjacentHTMl 也不
我正在尝试更改标签的innerHTML。我无权访问该表单,因此无法编辑 HTML。标签具有的唯一标识符是“for”属性。 这是输入和标签的结构:
我有一个页面,我可以在其中返回用户帖子,可以使用一些 jquery 代码对这些帖子进行即时评论,在发布新评论后,我在帖子下插入新评论以及删除 按钮。问题是 Delete 按钮在新插入的元素上不起作用,
我有一个大约有 20 列的“管道分隔”文件。我只想使用 sha1sum 散列第一列,它是一个数字,如帐号,并按原样返回其余列。 使用 awk 或 sed 执行此操作的最佳方法是什么? Accounti
我需要将以下内容插入到我的表中...我的用户表有五列 id、用户名、密码、名称、条目。 (我还没有提交任何东西到条目中,我稍后会使用 php 来做)但由于某种原因我不断收到这个错误:#1054 - U
所以我试图有一个输入字段,我可以在其中输入任何字符,但然后将输入的值小写,删除任何非字母数字字符,留下“。”而不是空格。 例如,如果我输入: 地球的 70% 是水,-!*#$^^ & 30% 土地 输
我正在尝试做一些我认为非常简单的事情,但出于某种原因我没有得到想要的结果?我是 javascript 的新手,但对 java 有经验,所以我相信我没有使用某种正确的规则。 这是一个获取输入值、检查选择
我想使用 angularjs 从 mysql 数据库加载数据。 这就是应用程序的工作原理;用户登录,他们的用户名存储在 cookie 中。该用户名显示在主页上 我想获取这个值并通过 angularjs
我正在使用 autoLayout,我想在 UITableViewCell 上放置一个 UIlabel,它应该始终位于单元格的右侧和右侧的中心。 这就是我想要实现的目标 所以在这里你可以看到我正在谈论的
我需要与 MySql 等效的 elasticsearch 查询。我的 sql 查询: SELECT DISTINCT t.product_id AS id FROM tbl_sup_price t
我正在实现代码以使用 JSON。 func setup() { if let flickrURL = NSURL(string: "https://api.flickr.com/
我尝试使用for循环声明变量,然后测试cols和rols是否相同。如果是,它将运行递归函数。但是,我在 javascript 中执行 do 时遇到问题。有人可以帮忙吗? 现在,在比较 col.1 和
我举了一个我正在处理的问题的简短示例。 HTML代码: 1 2 3 CSS 代码: .BB a:hover{ color: #000; } .BB > li:after {
我是一名优秀的程序员,十分优秀!