Receive and process JSON using fetch API in Javascript

3 javascript django ajax json fetch-api

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)
Run Code Online (Sandbox Code Playgroud)

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;
Run Code Online (Sandbox Code Playgroud)

I want to compare 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; }
Run Code Online (Sandbox Code Playgroud)

Thanks in advance!

iLy*_*yas 6

javascript 在全局窗口范围内提供了 fetch API,第一个参数是 API 的 URL,它是基于 Promise 的机制。

简单的例子

// 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);
});
Run Code Online (Sandbox Code Playgroud)

在你的情况下,如果你想接收JSON 响应

 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);
      });
Run Code Online (Sandbox Code Playgroud)

使用基于侦听器的示例XMLHttpRequest

// 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);
});
Run Code Online (Sandbox Code Playgroud)

使用 Listener 的示例setInterval(我不确定你想要做这样的事情,只是与你分享)

 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);
      });
Run Code Online (Sandbox Code Playgroud)

我对 Django 不太熟悉,但希望这可以帮助你。