Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- </head>
- <body>
- <div id="load">
- </div>
- <script>
- var data = null;
- function getPostsXhR() {
- var xhr = new XMLHttpRequest();
- xhr.addEventListener('readystatechange', function(){
- if(this.readyState === 4 && this.status === 200){
- console.log(this.responseText);
- }else{
- console.log("THere is an error", "Status code: " + this.status);
- }
- });
- xhr.open("GET", "https://jsonplaceholder.typicode.com/posts");
- xhr.send(data);
- }
- function getPostsPromises() {
- return new Promise(function(resolve, reject){
- let xhr = new XMLHttpRequest();
- xhr.onreadystatechange = function(e){
- if(this.readyState === 4 && this.status == 200){
- resolve(this.response);
- }else if(this.readyState === 4 && this.status == 200){
- console.log("Status:", this.status);
- reject(this.status)
- }
- };
- xhr.open("GET", "https://jsonplaceholder.typicode.com/posts", true);
- xhr.responseType = 'json';
- xhr.send();
- });
- }
- function getPostsUsingFetchOnly(){
- var fetchData = {
- method: 'GET',
- headers: new Headers()
- }
- fetch("https://jsonplaceholder.typicode.com/posts", fetchData)
- .then(function(response){
- return response.json();
- }).then(function(data){
- console.log(data);
- }).catch(function(e){
- console.log("err: ", e);
- });
- }
- window.onload = function(){
- // getPostsPromises().then(function(data){
- // console.log("Data: ", data);
- // }).catch(function(err){
- // console.log("Error: ", err);
- // }).finally(function(){
- // console.log('Finish!!!');
- // });
- getPostsUsingFetchOnly();
- }
- </script>
- </body>
- </html>
Add Comment
Please, Sign In to add comment