forked from jonyablonski/javascript-toolbox
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgetURL.js
More file actions
76 lines (59 loc) · 1.88 KB
/
getURL.js
File metadata and controls
76 lines (59 loc) · 1.88 KB
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
/**
* Get HTML from another URL
* @param {String} url The URL
* @param {Function} success Callback on success
* @param {Function} error Callback on failure
*/
var getURL = function ( url, success, error ) {
// Feature detection
if ( !window.XMLHttpRequest ) return;
// Create new request
var request = new XMLHttpRequest();
// Setup callbacks
request.onreadystatechange = function () {
// If the request is complete
if ( request.readyState === 4 ) {
// If the request failed
if ( request.status !== 200 ) {
if ( error && typeof error === 'function' ) {
error( request.responseText, request );
}
return;
}
// If the request succeeded
if ( success && typeof success === 'function' ) {
success( request.responseText, request );
}
}
};
// Get the HTML
request.open( 'GET', url );
request.send();
};
// Example 1: Generic Example
getURL(
'/about',
function (data) {
// On success...
var div = document.createElement( 'div' );
},
function (data) {
// On failure...
}
);
// Example 2: Find a specific element in the HTML and inject it into the current page
getURL(
'/about',
function (data) {
// Create a div and inject the HTML into it
var div = document.createElement( 'div' );
div.innerHTML = data;
// Find the element you're looking for in the div
var elem = div.querySelector( '#some-element' );
var location = document.querySelector( '#another-element' );
// Quit if the element or the place where you want to inject it don't exist
if ( !elem || !location ) return;
// Inject the element into the DOM
location.innerHTML = elem.innerHTML;
}
);