Advertisement
Guest User

Ajax

a guest
Jun 27th, 2019
261
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. let myUrl="https://newsapi.org/v2/top-headlines?country=il&apikey=f6619618319e4467ac2929cdba33833a"
  2.  
  3. //xmlHttpRequest - old school
  4. function runMe(){
  5.   var myReq = new XMLHttpRequest();
  6.   myReq.onload=reqListener;
  7.   myReq.onerror=reqError;
  8.   myReq.open('get',myUrl,true); //(method,url,async)
  9.   myReq.send();
  10. }
  11.  
  12. //listener
  13. function reqListener(){
  14.   //parse our data into a json type
  15.   var data = JSON.parse(this.responseText);
  16.   res.innerHTML=data.articles[0].title;
  17.   console.log(data.articles[0].title);
  18. }
  19.  
  20. function reqError(err){
  21.   console.log("Huston we have a problem:");
  22.   console.log(err);
  23. }
  24.  
  25.  
  26. //fetch - es6
  27. runMeEs6();
  28. function runMeEs6(){
  29.   fetch(myUrl)
  30.   .then(function (response){
  31.     if (response.status!=200){
  32.       console.log("error code:"+response.status);
  33.       return;
  34.     }
  35.     //examine the text in the response
  36.     response.json().then(function (data){
  37.       console.log(data.articles[0].title);
  38.       res.innerHTML=data.articles[0].title;
  39.     })
  40.   })
  41.   .catch(function(err){
  42.  
  43.   });
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement