【发布时间】:2014-06-20 14:43:52
【问题描述】:
我的计划是在不修改代码的情况下对所有 ajax 调用使用上下文预加载器。按照惯例,我的 ajax 调用是这样的。
// do some pre-loader for example spinning wheel
$('#submitBnt').on('click', function () {
$.get('/echo/json', function (data) {
// after everything is done do some cleanup for the UI
});
});
但是,我想在全局级别构建预加载器,这样任何 ajax 调用都会将旋转轮附加到容器并在一切完成后取消它。
到目前为止,这是我的代码,当然这不起作用。
var s_ajaxListener = new Object();
var target;
s_ajaxListener.tempOpen = XMLHttpRequest.prototype.open;
s_ajaxListener.tempSend = XMLHttpRequest.prototype.send;
s_ajaxListener.callback = function () {
console.log('last');
$('.ajaxContainer').removeClass('pre-loader');
}
XMLHttpRequest.prototype.open = function (a, b) {
console.log('first');
$(document).on('click', function (e) {
target = e.target;
$(target).closest('.ajaxContainer').addClass('pre-loader');
});
if (!a) var a = '';
if (!b) var b = '';
s_ajaxListener.tempOpen.apply(this, arguments);
s_ajaxListener.method = a;
s_ajaxListener.url = b;
if (a.toLowerCase() == 'get') {
s_ajaxListener.data = b.split('?');
s_ajaxListener.data = s_ajaxListener.data[1];
}
}
XMLHttpRequest.prototype.send = function (a, b) {
if (!a) var a = '';
if (!b) var b = '';
s_ajaxListener.tempSend.apply(this, arguments);
if (s_ajaxListener.method.toLowerCase() == 'post') s_ajaxListener.data = a;
s_ajaxListener.callback();
}
$('#submitBnt').on('click', function () {
$.get('/echo/json', function (data) {
console.log(data);
});
});
我的问题是 1. 为什么它不起作用。 2. 添加 $(document).on('click') 是个好主意,因为我认为它会将点击事件添加到全局事件中,这对于移动网站来说是否太多了?
这是我的小提琴 http://jsfiddle.net/noppanit/xke87/2/
谢谢。
【问题讨论】:
标签: javascript ajax html zepto