-
Notifications
You must be signed in to change notification settings - Fork 233
/
Copy pathjquery.lazy.ajax.js
88 lines (78 loc) · 3.02 KB
/
jquery.lazy.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
/*!
* jQuery & Zepto Lazy - AJAX Plugin - v1.4
* http://jquery.eisbehr.de/lazy/
*
* Copyright 2012 - 2018, Daniel 'Eisbehr' Kern
*
* Dual licensed under the MIT and GPL-2.0 licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl-2.0.html
*/
;(function($) {
// load data by ajax request and pass them to elements inner html, like:
// <div data-loader="ajax" data-src="url.html" data-method="post" data-type="html"></div>
$.lazy('ajax', function(element, response) {
ajaxRequest(this, element, response, element.attr('data-method'));
});
// load data by ajax get request and pass them to elements inner html, like:
// <div data-loader="get" data-src="url.html" data-type="html"></div>
$.lazy('get', function(element, response) {
ajaxRequest(this, element, response, 'GET');
});
// load data by ajax post request and pass them to elements inner html, like:
// <div data-loader="post" data-src="url.html" data-type="html"></div>
$.lazy('post', function(element, response) {
ajaxRequest(this, element, response, 'POST');
});
// load data by ajax put request and pass them to elements inner html, like:
// <div data-loader="put" data-src="url.html" data-type="html"></div>
$.lazy('put', function(element, response) {
ajaxRequest(this, element, response, 'PUT');
});
/**
* execute ajax request and handle response
* @param {object} instance
* @param {jQuery|object} element
* @param {function} response
* @param {string} [method]
*/
function ajaxRequest(instance, element, response, method) {
method = method ? method.toUpperCase() : 'GET';
var data;
if ((method === 'POST' || method === 'PUT') && instance.config('ajaxCreateData')) {
data = instance.config('ajaxCreateData').apply(instance, [element]);
}
$.ajax({
url: element.attr('data-src'),
type: method === 'POST' || method === 'PUT' ? method : 'GET',
data: data,
dataType: element.attr('data-type') || 'html',
/**
* success callback
* @access private
* @param {*} content
* @return {void}
*/
success: function(content) {
// set responded data to element's inner html
element.html(content);
// use response function for Zepto
response(true);
// remove attributes
if (instance.config('removeAttribute')) {
element.removeAttr('data-src data-method data-type');
}
},
/**
* error callback
* @access private
* @return {void}
*/
error: function() {
// pass error state to lazy
// use response function for Zepto
response(false);
}
});
}
})(window.jQuery || window.Zepto);