【发布时间】:2017-08-21 16:20:24
【问题描述】:
我有这个代码:
var request1 = this.add(prod_id, pack_id_combination, button, pack_qty).then(function(rdata1){
// this always works
this.add(prod_id, case_id_combination, button, case_qty).then(function(rdata2){
// this sometimes (random) doesn't work
}.bind(this), function(req, status, error){ console.log('case error',req, status, error); });
}.bind(this), function(){ console.log('pack error'); });
我省略了其余的代码,因为它是一个巨大的类,而且也不可能构建一个 jsfiddle,太多的东西。
但事实是这样的:
我的 js 指向一个返回数据的 php 文件。它通过
add()函数进行ajax 调用(见下文)第一次调用时总是有效,第二次调用时有时无效。
在日志上,status = 'error', error = ''(空,所以这里没有信息)
我也确信第二个 add(),如果使用相同的参数单独调用,将始终有效。
此外,它只在 safari 和 IE 中存在这些问题,在 chrome、ff、android 中没有
此外,它只有在在线测试时才会出现这些问题,而在我的本地环境中始终可以正常工作。
Safari 说它失去了连接。这是我能得到的唯一信息
add() 函数很简单:
add:function(idProduct, idCombination, callerElement, quantity){
return $.ajax({
type: 'POST'
,headers: { "cache-control": "no-cache" }
,url: baseUri + '?rand=' + new Date().getTime()
,cache: false
,dataType : "json"
,data: 'controller=cart&add=1&ajax=true&qty=' + ((quantity && quantity != null) ? quantity : '1') + '&id_product=' + idProduct + '&token=' + static_token + ( (parseInt(idCombination) && idCombination != null) ? '&ipa=' + parseInt(idCombination): '')
,success:function(data, status, req){
console.log('ok');
}
,error:function(jqXHR, textStatus, errorThrown){
console.log(jqXHR.responseText, textStatus, errorThrown);
}
});
},//end add()
那么,我的问题是:有没有办法避免这个问题?这是一个常见的陷阱吗?是否有避免此类问题的常见做法?
【问题讨论】:
-
正如所写,它绝对行不通。在表达式
this.a.then(function() { this.b()})中,第二个this对象将是全局范围,这几乎肯定不是您想要的。在this.a.then(() => { this.b()})中,两个 this 都指向同一个对象。 -
嗯,你确定吗?我正在绑定一切。此外,正如所写,实际上它不仅适用于远程环境,而且仅适用于 safari 和 IE。
-
非常确定。这是 fat-arrow 和 this 的主要区别。
-
我用的是jquery,没有js6。您能否在常规答案上发布一些更明确的代码,以便我更好地理解?另外,在列出的用例中,我所有的 bind(this) 以及它的工作原理(它是一个在线生产网站,从几年前开始)怎么样?
-
无论这个设置是否正确,如果没有内部 this.add 上的 return 语句,我看不出 request1 有什么意义
标签: javascript jquery ajax promise deferred