我有SendRequest对象,并且该类具有类似
i have SendRequest object and that class has a function like
request: function(args) { return $.ajax.apply(null, args); };那么很多类都使用SendRequest对象来获取服务器响应
then a lot of class use SendRequest object to get server response
var prom = SendRequest.request( { type: 'GET', url: _this.uri }); return $.when(prom).done(function(response) { .... do something });我的目标是在SendRequest.request中需要首先检查window.localStorage. 是否已经有一个值,如果之前没有任何值则发送请求. 否则,如果在localStorage上已经有值,则返回$ .ajax()对象,并保存之前的值.
My goal is in SendRequest.request need to check on window.localStorage first. Whether already has a value or not, if has not any value before then send the request. Otherwise, if already value on localStorage then return $.ajax() object with that saved value before.
request: function(args) { var ls = window.localStorage; var savedResponse = ls.getItem(args.url); if (savedResponse !=== null) { var result = $.ajax(); result.responseText = savedResponse; result.readyState = 4; result.status = 'OK'; return result; } else { return $.ajax.apply(null, args); } };但不幸的是它没有用:( 我一直在寻找,但找不到像我这样的情况
but unfortunately its did not work :( I've been looking but can not find some case like me
我已经尝试过这种方式 如何愚弄jqXHR始终获得成功 但没有太大帮助
I already try this way to how to fool jqXHR to succeed always but its not help much
推荐答案之所以不起作用,是因为尽管您创建了一个伪造的jqXHR对象,该对象是$.ajax的响应,但该对象却不是实际上是提供给.done回调的参数-它实际上是第三个参数.
The reason this doesn't work is that although you've created a fake jqXHR object that's the response from $.ajax, that object isn't actually the parameter that's supplied to the .done callback - it's actually the third parameter.
此外,恕我直言,您不应该真正使用$.when来承诺"单个非承诺对象.它旨在处理多个Promise之间的同步,并且将每个非Promise都包装成一个新的Promise只是一个副作用.
Also, IMHO you shouldn't really use $.when to "promisify" a single non-promise object. It's intended to handle synchronisation between multiple promises and the fact that it wraps each non-promise into a new promise is just a side effect.
相反,您应该使用适当的数据创建一个已经解决"的新承诺:
Instead, you should create a new promise that is already "resolved" with the appropriate data:
if (savedResponse != null) { return $.Deferred(function() { // retrieve relevant fields from localStorage ... this.resolve([data, textStatus, jqXHR]); }).promise(); } else { // perform real AJAX request return $.ajax.apply($, args); }或者,考虑仅记住返回数据本身(用于成功调用),而不是整个响应三元组.
Alternatively, consider just memoizing the return data itself (for successful calls), not the whole response triple.
您可能还会发现我在jQuery UK 2013上使用过的演示文稿- www.slideshare/RayBellis/memoizing-withindexeddb
You may also find this presentation that I gave at jQuery UK 2013 of use - www.slideshare/RayBellis/memoizing-withindexeddb
更多推荐
使jquery jqxhr像已经发送请求一样
发布评论