Saturday, 2 March 2019

How to call a XMLHttpRequest in javascript

1. We need a JSON Data provider

http://puzzle.mead.io/puzzle?wordCount=3

2.  Steps of Making a HTTP Request

  • constructor function
    • const req = new XMLHttpRequest()
  • Initialize request [param: 1. Method: GET 2. URL ]
    • req.open('GET','http://puzzle.mead.io/puzzle?wordCount=3')
  • Send Request [it takes time to get response]
    • req.send()
  • https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState
  • add event listener, event name: readystatechange,  
    • req.addEventListener('readystatechange',(e)=>{
        • if(e.target.readyState == 4){
        • const data = JSON.parse(e.target.responseText)
        • console.log(data)
        • }
      • }


Final Code:


const getMessage = function(){

const req = new XMLHttpRequest();

req.addEventListener('readystatechange',(e)=>{
if (req.readyState == 4){
const data  = JSON.parse(e.target.responseText)
console.log(data)
}
})

req.open('GET','http://puzzle.mead.io/puzzle?wordCount=3')
req.send();

}

No comments:

Post a Comment