forked from WebProgrammingII/WEPO
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscripted_http_example_1.js
80 lines (51 loc) · 1.98 KB
/
scripted_http_example_1.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
/**
* An example of how to issue XMLHttpRequests in JS
*/
var rootUrl = 'https://serene-island-81305.herokuapp.com';
/* Part 1 - A normal GET request */
// 1. Create a basic XMLHttpRequest object
// 2. Use the open() function as a GET request to Heroku app
// 3. Register the onreadystatechange event handler
// 4. Use the send() function to issue the request
// 5. Examine the request within the event handler
// 6. Console.log the data
/* Part 2 - A normal POST request */
// 1. Create another XMLHttpRequest
// 2. Use the open() function as a POST request to Heroku app
// 3. Set the request header to application/json
// 4. Register the handler
// 5. Use the send() function with the body set
// 6. alert if successful
/* Part 3 - A synchronous request */
// 1. Create a basic XMLHttpRequest object
// 2. Use the open() function as a GET request to special method in Heroku app
// 3. Show effects in browser
/* Part 4 - Demonstrate encoding techniques */
var form = {
id: 1,
name: 'Mr. Miyaki',
age: 70
};
// 1. JSON.stringify()
console.log(JSON.stringify(form));
// 2. FormData for multipart/form-data
function createFormData(data) {
var formData = new FormData();
Object.keys(data).forEach(function (elem) {
formData.append(elem, data[elem]);
});
return formData;
};
// 3. application/x-www-form-urlencoded with encodeURIComponent
function createFormUrlEncoded(data) {
var formUrlEncoded = [];
Object.keys(data).forEach(function (elem) {
var value = encodeURIComponent(data[elem]);
var header = encodeURIComponent(elem);
formUrlEncoded.push(header + '=' + value);
});
return formUrlEncoded.join('&');
};
/* Part 5 - Demonstrate the progress event */
// 1. Issue request to special synchronous method /file
// 2. Show the results in a progress bar