简体   繁体   English

在 Javascript 中使用 fetch API 接收和处理 JSON

[英]Receive and process JSON using fetch API in Javascript

In my Project when conditions are insufficient my Django app send JSON response with message.在我的项目中,当条件不足时,我的 Django 应用程序发送带有消息的 JSON 响应。

I use for this JsonResponse() directive,我用于这个 JsonResponse() 指令,

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.现在我想使用 Javascript fetch API 接收这个 JSON 响应,例如显示警报。

I don't know how to use fetch API to do this.我不知道如何使用 fetch API 来做到这一点。 I want to write a listener who will be waiting for my JSON response from Django App.我想编写一个监听器,它会等待来自 Django 应用程序的 JSON 响应。

I try:我尝试:

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

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

I want to compare JSON from my Django app with hardcoded JSON:我想将来自我的 Django 应用程序的 JSON 与硬编码的 JSON 进行比较:
For example: fetch( 'is_taken_email': email) - > then make something例如: fetch( 'is_taken_email': email) -> 然后做点什么

OR

receive JSON from my Django app and as AJAX make it:从我的 Django 应用程序接收 JSON 并作为 AJAX 使其:

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

Thanks in advance!提前致谢!

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.在 javascript 的全局窗口范围内提供了一个 fetch API,第一个参数是你的 API 的 URL,它是基于 Promise 的机制。

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在您的情况下,如果您想接收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);
      });

Example using listener based on XMLHttpRequest使用基于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) Using Listener as setInterval例子(我不确定你是否想做这样的事情,只是分享给你)

 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.我不熟悉 Django,但我希望这可以帮助你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM