jQuery代码-2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// jQuery 单例
(function ($) {
var index = {
init: function () {
// 一些jQuery对象的储存
this.render();
// 事件的绑定
this.bind();
this.ajaxSeeting()
},
datas: {
ajaxPath: 'http://localhost/test/api.php',
currentRequests: {},
id: 1
},
ajaxSeeting: function () {
var me = this;

// 设置Ajax请求的默认值
$.ajaxSetup({
url: me.datas.ajaxPath,
dataType: 'json',
beforeSend: function (xhr, settings) {
settings.data = settings.data + '&k=2&v=9'
},
statusCode: {
404: function () {
// Do something
console.log(404)
},
405: function () {
// Do something
console.log(405)
},
500: function () {
// Do something
console.log(500)
},
502: function () {
// Do something
console.log(502)
}
}
});

// 预过滤器
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
console.log(options, originalOptions, jqXHR)
// 自定义abortOnRetry选项被设置为true
// 那么调用$.ajax()会自动中止请求相同的URL:
if (options.abortOnRetry) {
if (me.datas.currentRequests[options.url]) {
me.datas.currentRequests[options.url].abort();
}
me.datas.currentRequests[options.url] = jqXHR;
}

// 代理服务器跨域请求
// if (options.crossDomain) {
// options.url = 'http://localhost/test' + decodeURIComponent(options.url);
// options.crossDomain = false;
// }
});
},
render: function () {
var me = this;
me.btn = $('#btn');
},
bind: function () {
var me = this;
me.btn.on('click', $.proxy(me['_do'], this, me.datas.id))
},
_do: function (id) {
$.ajax({
// 同一域中强制跨域请求
crossDomain: true,
abortOnRetry: true,
type: 'POST',
// content: this,
data: {
id: id
}
}).done(function (data, textStatus, jqXHR) {
console.log('Success...')
}).fail(function (jqXHR, textStatus, errorThrown) {
console.log('Error...')
}).always(function (jqXHR, textStatus, errorThrown) {
console.log('Complete...')
})
}
};
index.init();
exports = index;
})(jQuery);