1+ <!DOCTYPE html>
2+ < html lang ="en ">
3+ < head >
4+ < meta charset ="UTF-8 ">
5+ < meta name ="viewport " content ="width=device-width, initial-scale=1.0 ">
6+ < meta http-equiv ="X-UA-Compatible " content ="ie=edge ">
7+ < title > Dog-photo-gallery</ title >
8+ < style >
9+ body {
10+ text-align : center;
11+ background-color : whitesmoke;
12+ }
13+ button {
14+ padding : 10px ;
15+ margin : 10px ;
16+ font-weight : 600 ;
17+ }
18+ </ style >
19+ </ head >
20+ < body >
21+ < dvi >
22+ < button id ="btn "> Get by Axios</ button >
23+ < button id ="btn2 "> Get by XHR</ button >
24+ < div id ="main ">
25+ < ul >
26+ < li >
27+
28+ </ li >
29+ </ ul >
30+ </ div >
31+
32+ </ dvi >
33+
34+ < script src ="https://unpkg.com/axios/dist/axios.min.js "> </ script >
35+ < script >
36+ let mainDiv = document . getElementById ( 'main' )
37+ let getByAxios = document . getElementById ( 'btn' ) ;
38+ let getByXHR = document . getElementById ( 'btn2' ) ;
39+ getByAxios . addEventListener ( 'click' , fetchByAxios ) ;
40+ getByXHR . addEventListener ( 'click' , fetchByXHR ) ;
41+
42+ // Response by axios
43+ function fetchByAxios ( ) {
44+ axios
45+ . get ( 'https://dog.ceo/api/breeds/image/random' )
46+ . then ( ( res ) => {
47+ mainDiv . innerHTML = '' ;
48+ let img = document . createElement ( 'img' ) ;
49+ img . src = res . data . message ;
50+ img . style . width = '400px' ;
51+ img . style . height = '400px' ;
52+ let h1 = document . createElement ( 'h1' ) ;
53+ h1 . innerText = 'Show by Axios' ;
54+ mainDiv . appendChild ( h1 ) ;
55+ mainDiv . appendChild ( img ) ;
56+ } )
57+ . catch ( ( err ) => console . error ( err ) ) ;
58+ }
59+
60+ // Response By XHR
61+ function fetchByXHR ( ) {
62+ let getByXhr = new XMLHttpRequest ( ) ;
63+ getByXhr . responseType = 'json' ;
64+ getByXhr . onreadystatechange = function ( ) {
65+ if ( this . readyState === 4 && this . status === 200 ) {
66+ mainDiv . innerHTML = '' ;
67+ let img = document . createElement ( 'img' ) ;
68+ img . src = getByXhr . response . message ;
69+ img . style . width = '400px' ;
70+ img . style . height = '400px' ;
71+ let h1 = document . createElement ( 'h1' ) ;
72+ h1 . innerText = 'Show by XHR' ;
73+ mainDiv . appendChild ( h1 ) ;
74+ mainDiv . appendChild ( img ) ;
75+ }
76+ } ;
77+ getByXhr . open ( 'GET' , 'https://dog.ceo/api/breeds/image/random' , true ) ;
78+ getByXhr . send ( ) ;
79+ }
80+
81+ </ script >
82+
83+ </ body >
84+ </ html >
0 commit comments