0
我有一個集合,它使用XMLHttpRequest成功發送文件到服務器。 但我不知道如何將函數附加到XHR2事件。集合中的XHR2訪問事件
它只是似乎是工作時的代碼是直接的send()內:
var Photos = Backbone.Collection.extend({
url: config.url,
/**
* Send file to server.
* @todo Should Backbone.sync be overwritten instead?
*/
send: function (file) {
var data = new FormData(),
xhr = new XMLHttpRequest();
// ======> Doesn't work:
xhr.addEventListener('load', this.onLoad(xhr));
// ======> Doesn't work either:
xhr.onload = this.onLoad(xhr);
// ======> But this works:
xhr.onload = function() {
var response = $.parseJSON(xhr.responseText);
console.log(response); // Works!
};
data.append('file', file);
xhr.open('POST', this.url);
xhr.send(data);
},
/**
* Respond to XHR2 'onload' event.
*/
onLoad: function (xhr) {
var response = $.parseJSON(xhr.responseText);
console.log(response); // Doesn't work!
}
});
爲什麼會這樣,我怎麼可以移動代碼發送的外()和成一個單獨的功能?
感謝穆薩,是有道理的:)順便說一句:_xhr.addEventListener( '負荷',this.onLoad) ; _也適用! –