设置
Backbone.js 用于前端的 MV*,RequireJS 用于依赖管理,REST 服务用于从数据库中检索数据。这些服务与 Web 应用程序位于同一域中。
问题
当我通过 IE 7 中的 REST 服务从服务器获取集合时,会引发错误回调。当我检查 xhr 对象时,状态为 0,statusText 为 0。这只是 IE 7 中的问题。FF 和 Chrome 对 ajax GET 没有问题。
这是代码(AMD定义)
define([
'underscore',
'backbone',
'models/imageLink',
'app/registry'
], function(_, Backbone, ImageLink, AppReg) {
var collection = Backbone.Collection.extend({
ajaxRequest: false,
highestKey: 0,
polling : false,
pollDelay: 7500,
// Reference to this collection's model.
model: ImageLink,
url: function(){
return "http://samedomain:4020/api/imageLinks" + "?userId=" + this.user;
},
user: "",
initialize: function() {
// ensure correct context of 'this'
_.bindAll(this, 'startPolling', 'stopPolling', 'executePolling', "onFetch");
var _this=this;
console.log('Image Links collection has been initialized.');
},
// used for sorting collection, sorts based on the lowercase value of the imageLink's text attribute
comparator: function(imageLink) {
return imageLink.get('text').toLowerCase();
},
// override parse function to prevent backbone from updating empty data returned from server
parse: function(response,options) {
//debugger;
if (options.xhr.status===204) {
return this.toJSON();
}
else
return response;
},
getHighestKey: function() {
if (this.length) {
return this.at(this.length-1).get("id");
}
else {
return this.highestKey;
}
},
startPolling : function() {
this.polling = true;
this.highestKey = this.getHighestKey();
this.executePolling();
},
stopPolling : function() {
this.polling = false;
},
executePolling : function() {
if (this.ajaxRequest == "") {
this.ajaxRequest = this.fetch({ reset:true, complete: this.onFetch, timeout: 30000, data: $.param({ key: this.highestKey }),
error: function(model, xhr, options) {
alert("Error\n"+xhr.readyState+"\n"+xhr.status+"\n"+xhr.statusText.toString()+"\n"+xhr.responseText);
}
});
}
},
onFetch : function () {
this.ajaxRequest = "";
this.highestKey = this.getHighestKey();
if( this.polling ) {
// poll database
setTimeout(this.executePolling,this.pollDelay);
}
}
});
return collection;
});
笔记
使用 IE 9 中的开发人员工具在 IE 7 下渲染时,该页面工作正常。该问题仅在 IE 7 独立加载时出现。
此外,我在应用程序启动时执行以下操作:
// do not cache any ajax requests
$.ajaxSetup({ cache: false });
// needed for IE CORS support
$.support.cors = true;