Receive and process JSON using fetch API in Javascript

时间秒杀一切 提交于 2019-11-29 17:44:30

A fetch API is provided in the global window scope in javascript, with the first argument being the URL of your API, it's Promise-based mechanism.

Simple Example

// url (required)
fetch('URL_OF_YOUR_API', {//options => (optional)
    method: 'get' //Get / POST / ...
}).then(function(response) {
    //response
}).catch(function(err) {
// Called if the server returns any errors
  console.log("Error:"+err);
});

In your case, If you want to receive the JSON response

 fetch('YOUR_URL')
    .then(function(response){
         // response is a json string
        return response.json();// convert it to a pure JavaScript object
    })
    .then(function(data){
         //Process Your data  
      if (data.is_taken_email)   
           alert(data);
    })
    .catch(function(err) {
        console.log(err);
      });

Example using listener based on XMLHttpRequest

function successListener() {  
  var data = JSON.parse(this.responseText);  
  alert("Name is: "+data[0].name);  
}

function failureListener(err) {  
  console.log('Request failed', err);  
}

var request = new XMLHttpRequest();  
request.onload = successListener;  
request.onerror = failureListener;  
request.open('get', 'https://jsonplaceholder.typicode.com/users',true);  
request.send();

Example of Using Listener as setInterval (I'm not sure that you want to do something like this, it's just to share with you)

var listen = setInterval(function() {

  fetch('https://jsonplaceholder.typicode.com/users')
    .then(function(response) {
      return response.json();
    })
    .then(function(data) {
      if (data[0].name)
        console.log(data[0].name);
    })
    .catch(function(err) {
      console.log(err);
    });

}, 2000);//2 second

I am not familier with Django, but I hope this could help you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!