-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2-ajax.js
64 lines (49 loc) · 1.42 KB
/
2-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
/**
* 1. XMLHttpRequest
* 2. Sending a GET request
* 3. Listening to state changes
* 4. Handling AJAX response
* 5. Aborting an AJAX request
* 6. Including cookies in requests
* 7. Sending a POST request
*/
const xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener('readystatechange', function() {
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
const response = JSON.parse(xhr.responseText);
console.log(response);
const h1 = document.querySelector('h1');
h1.textContent = response.title;
} else {
console.log('FAILED :(');
}
}
});
let file = null;
document.querySelector('input').addEventListener('change', function(e) {
file = e.target.files[0];
});
const button = document.querySelector('button');
button.addEventListener('click', function() {
const formData = new FormData();
formData.set('title', 'JavaScript');
formData.set('file', file, 'file.png');
console.log(file);
xhr.open('POST', 'https://endpoints.uncaughtexception.wtf/dc1f54ed17194014aea6d8a1c7c19a9f');
xhr.send(formData);
setTimeout(function() {
xhr.abort();
}, 1000);
});
$.ajax({
type: 'POST',
url: 'https://endpoints.uncaughtexception.wtf/dc1f54ed17194014aea6d8a1c7c19a9f',
data: {
},
success: function(response) {
},
error: function(error) {
}
});