最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Receive and process JSON using fetch API in Javascript - Stack Overflow

programmeradmin1浏览0评论

In my Project when conditions are insufficient my Django app send JSON response with message.

I use for this JsonResponse() directive,

Code:

data = {
    'is_taken_email': email
}
return JsonResponse(data)

Now I want using Javascript fetch API receive this JSON response and for example show alert.

I don't know how to use fetch API to do this. I want to write a listener who will be waiting for my JSON response from Django App.

I try:

function reqListener() {
  var stack = JSON.parse(data);
  console.log(stack);
}

var oReq = new XMLHttpRequest();
oReq.onload = reqListener;

I want to pare JSON from my Django app with hardcoded JSON:
For example: fetch( 'is_taken_email': email) - > then make something

OR

receive JSON from my Django app and as AJAX make it:

success: function(data) { if (data.is_taken_email) { make something; }

Thanks in advance!

In my Project when conditions are insufficient my Django app send JSON response with message.

I use for this JsonResponse() directive,

Code:

data = {
    'is_taken_email': email
}
return JsonResponse(data)

Now I want using Javascript fetch API receive this JSON response and for example show alert.

I don't know how to use fetch API to do this. I want to write a listener who will be waiting for my JSON response from Django App.

I try:

function reqListener() {
  var stack = JSON.parse(data);
  console.log(stack);
}

var oReq = new XMLHttpRequest();
oReq.onload = reqListener;

I want to pare JSON from my Django app with hardcoded JSON:
For example: fetch( 'is_taken_email': email) - > then make something

OR

receive JSON from my Django app and as AJAX make it:

success: function(data) { if (data.is_taken_email) { make something; }

Thanks in advance!

Share Improve this question edited Feb 17, 2018 at 14:21 asked Feb 17, 2018 at 12:07 user9373369user9373369 2
  • here's some documentation for the fetch API – Jaromanda X Commented Feb 17, 2018 at 12:09
  • You may need to study about redux-saga. A nice way to organize and structure our Api calls – Igor Quirino Commented Nov 30, 2019 at 13:59
Add a ment  | 

2 Answers 2

Reset to default 6

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./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./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.

this my example to fetch

export function fetchProduct() {
  return (dispatch, getState, api) => {
    const access_token = localStorage.getItem("access_token");
    fetch(`${BASE_URL}/products`, {
      method: "GET",
      headers: {
        "access_token": access_token
      }
    })
    .then((response) => response.json())
    .then((jsonData) => {
      console.log(jsonData.data, 'isi dari json data line 30');
      dispatch(productSetProduct(jsonData.data));
    })
    .catch((err) => {
      console.log(err);
    });
  };
}```
发布评论

评论列表(0)

  1. 暂无评论