1
1
const result = document . querySelector ( '.result' ) ;
2
2
3
- function openXMLHttpRequest ( ) {
3
+ // function openXMLHttpRequest() {
4
4
5
- const xhr = new XMLHttpRequest ( ) ,
6
- method = 'GET' ,
7
- url = 'http://localhost:3000' ;
5
+ // const xhr = new XMLHttpRequest(),
6
+ // method = 'GET',
7
+ // url = 'http://localhost:3000';
8
8
9
- xhr . open ( method , url , true ) ;
9
+ // xhr.open(method, url, true);
10
+
11
+ // xhr.onreadystatechange = function () {
12
+
13
+ // /*
14
+
15
+ // 0 UNSENT Um cliente foi criado. Mas o método open() não foi chamado ainda.
16
+ // 1 OPENED O método open() foi chamado.
17
+ // 2 HEADERS_RECEIVED o método send() foi chamado e os cabeçalhos e status estão disponíveis .
18
+ // 3 LOADING Baixando e responseText contem os dados parciais.
19
+ // 4 DONE Operação concluída.
10
20
11
- xhr . onreadystatechange = function ( ) {
21
+ // */
12
22
13
- /*
23
+ // if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
24
+ // result.innerHTML = JSON.stringify(JSON.parse(xhr.responseText), null, 2);
25
+ // }
26
+ // }
14
27
15
- 0 UNSENT Um cliente foi criado. Mas o método open() não foi chamado ainda.
16
- 1 OPENED O método open() foi chamado.
17
- 2 HEADERS_RECEIVED o método send() foi chamado e os cabeçalhos e status estão disponíveis .
18
- 3 LOADING Baixando e responseText contem os dados parciais.
19
- 4 DONE Operação concluída.
28
+ // xhr.send();
29
+ // }
20
30
21
- */
31
+ let HttpService = ( method , url , callback ) => {
32
+ callback = callback || function ( ) { } ;
33
+ const xhr = new XMLHttpRequest ( ) ;
34
+
35
+ xhr . open ( method , url , true ) ;
36
+
37
+ xhr . onreadystatechange = function ( ) {
22
38
23
39
if ( xhr . readyState === XMLHttpRequest . DONE && xhr . status === 200 ) {
24
- result . innerHTML = JSON . stringify ( JSON . parse ( xhr . responseText ) , null , 2 ) ;
40
+ callback ( JSON . parse ( xhr . responseText ) ) ;
25
41
}
26
- }
42
+ } ;
27
43
28
44
xhr . send ( ) ;
29
45
}
30
46
47
+ function openXMLHttpRequest ( ) {
48
+
49
+ HttpService ( 'GET' , 'https://jsonplaceholder.typicode.com/albums' , albums => {
50
+ HttpService ( 'GET' , 'https://jsonplaceholder.typicode.com/photos' , photos => {
51
+ const relationship = albums . map ( album => {
52
+ album . photos = photos . filter ( photo => photo . albumId === album . id )
53
+
54
+ return album ;
55
+ } )
56
+
57
+ result . innerHTML = JSON . stringify ( relationship , null , 2 ) ;
58
+ } )
59
+ } )
60
+
61
+ }
0 commit comments