forked from madrobby/zepto
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathajax.js
303 lines (282 loc) · 8.67 KB
/
ajax.js
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
// Zepto.js
// (c) 2010, 2011 Thomas Fuchs
// Zepto.js may be freely distributed under the MIT license.
(function($){
var jsonpID = 0,
isObject = $.isObject,
key;
// Empty function, used as default callback
function empty() {}
// ### $.ajaxJSONP
//
// Load JSON from a server in a different domain (JSONP)
//
// *Arguments:*
//
// options — object that configure the request,
// see avaliable options below
//
// *Avaliable options:*
//
// url — url to which the request is sent
// success — callback that is executed if the request succeeds
//
// *Example:*
//
// $.ajaxJSONP({
// url: 'http://example.com/projects?callback=?',
// success: function (data) {
// projects.push(json);
// }
// });
//
$.ajaxJSONP = function(options){
var jsonpString = 'jsonp' + ++jsonpID,
script = document.createElement('script');
window[jsonpString] = function(data){
options.success(data);
delete window[jsonpString];
};
script.src = options.url.replace(/=\?/, '=' + jsonpString);
$('head').append(script);
};
// ### $.ajaxSettings
//
// AJAX settings
//
$.ajaxSettings = {
// Default type of request
type: 'GET',
// Callback that is executed before request
beforeSend: empty,
// Callback that is executed if the request succeeds
success: empty,
// Callback that is executed the the server drops error
error: empty,
// Callback that is executed on request complete (both: error and success)
complete: empty,
// MIME types mapping
accepts: {
script: 'text/javascript, application/javascript',
json: 'application/json',
xml: 'application/xml, text/xml',
html: 'text/html',
text: 'text/plain'
}
};
// ### $.ajax
//
// Perform AJAX request
//
// *Arguments:*
//
// options — object that configure the request,
// see avaliable options below
//
// *Avaliable options:*
//
// type ('GET') — type of request GET / POST
// url (window.location) — url to which the request is sent
// data — data to send to server,
// can be string or object
// dataType ('json') — what response type you accept from
// the server:
// 'json', 'xml', 'html', or 'text'
// success — callback that is executed if
// the request succeeds
// error — callback that is executed if
// the server drops error
//
// *Example:*
//
// $.ajax({
// type: 'POST',
// url: '/projects',
// data: { name: 'Zepto.js' },
// dataType: 'html',
// success: function (data) {
// $('body').append(data);
// },
// error: function (xhr, type) {
// alert('Error!');
// }
// });
//
$.ajax = function(options){
options = options || {};
var settings = $.extend({}, options);
for (key in $.ajaxSettings) if (!settings[key]) settings[key] = $.ajaxSettings[key];
if (/=\?/.test(settings.url)) return $.ajaxJSONP(settings);
if (!settings.url) settings.url = window.location.toString();
if (settings.data && !settings.contentType) settings.contentType = 'application/x-www-form-urlencoded';
if (isObject(settings.data)) settings.data = $.param(settings.data);
if (settings.type.match(/get/i) && settings.data) {
var queryString = settings.data;
if (settings.url.match(/\?.*=/)) {
queryString = '&' + queryString;
} else if (queryString[0] != '?') {
queryString = '?' + queryString;
}
settings.url += queryString;
}
var mime = settings.accepts[settings.dataType],
xhr = new XMLHttpRequest();
settings.headers = $.extend({'X-Requested-With': 'XMLHttpRequest'}, settings.headers || {});
if (mime) settings.headers['Accept'] = mime;
xhr.onreadystatechange = function(){
if (xhr.readyState == 4) {
var result, error = false;
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 0) {
if (mime == 'application/json' && !(xhr.responseText == '')) {
try { result = JSON.parse(xhr.responseText); }
catch (e) { error = e; }
}
else result = xhr.responseText;
if (error) settings.error(xhr, 'parsererror', error);
else settings.success(result, 'success', xhr);
} else {
error = true;
settings.error(xhr, 'error');
}
settings.complete(xhr, error ? 'error' : 'success');
}
};
xhr.open(settings.type, settings.url, true);
if (settings.beforeSend(xhr, settings) === false) {
xhr.abort();
return false;
}
if (settings.contentType) settings.headers['Content-Type'] = settings.contentType;
for (name in settings.headers) xhr.setRequestHeader(name, settings.headers[name]);
xhr.send(settings.data);
return xhr;
};
// ### $.get
//
// Load data from the server using a GET request
//
// *Arguments:*
//
// url — url to which the request is sent
// success — callback that is executed if the request succeeds
//
// *Example:*
//
// $.get(
// '/projects/42',
// function (data) {
// $('body').append(data);
// }
// );
//
$.get = function(url, success){ $.ajax({ url: url, success: success }) };
// ### $.post
//
// Load data from the server using POST request
//
// *Arguments:*
//
// url — url to which the request is sent
// [data] — data to send to server, can be string or object
// [success] — callback that is executed if the request succeeds
// [dataType] — type of expected response
// 'json', 'xml', 'html', or 'text'
//
// *Example:*
//
// $.post(
// '/projects',
// { name: 'Zepto.js' },
// function (data) {
// $('body').append(data);
// },
// 'html'
// );
//
$.post = function(url, data, success, dataType){
if ($.isFunction(data)) dataType = dataType || success, success = data, data = null;
$.ajax({ type: 'POST', url: url, data: data, success: success, dataType: dataType });
};
// ### $.getJSON
//
// Load JSON from the server using GET request
//
// *Arguments:*
//
// url — url to which the request is sent
// success — callback that is executed if the request succeeds
//
// *Example:*
//
// $.getJSON(
// '/projects/42',
// function (json) {
// projects.push(json);
// }
// );
//
$.getJSON = function(url, success){ $.ajax({ url: url, success: success, dataType: 'json' }) };
// ### $.fn.load
//
// Load data from the server into an element
//
// *Arguments:*
//
// url — url to which the request is sent
// [success] — callback that is executed if the request succeeds
//
// *Examples:*
//
// $('#project_container').get(
// '/projects/42',
// function () {
// alert('Project was successfully loaded');
// }
// );
//
// $('#project_comments').get(
// '/projects/42 #comments',
// function () {
// alert('Comments was successfully loaded');
// }
// );
//
$.fn.load = function(url, success){
if (!this.length) return this;
var self = this, parts = url.split(/\s/), selector;
if (parts.length > 1) url = parts[0], selector = parts[1];
$.get(url, function(response){
self.html(selector ?
$(document.createElement('div')).html(response).find(selector).html()
: response);
success && success();
});
return this;
};
// ### $.param
//
// Encode object as a string for submission
//
// *Arguments:*
//
// obj — object to serialize
// [v] — root node
//
// *Example:*
//
// $.param( { name: 'Zepto.js', version: '0.6' } );
//
$.param = function(obj, v){
var result = [], add = function(key, value){
result.push(encodeURIComponent(v ? v + '[' + key + ']' : key)
+ '=' + encodeURIComponent(value));
},
isObjArray = $.isArray(obj);
for(key in obj)
if(isObject(obj[key]))
result.push($.param(obj[key], (v ? v + '[' + key + ']' : key)));
else
add(isObjArray ? '' : key, obj[key]);
return result.join('&').replace('%20', '+');
};
})(Zepto);