简体   繁体   English

从API解析数据,未定义

[英]Parsing data from API, getting undefined

I am new to APIs and I want to add the USDA Nutrients database api to my website. 我是API的新手,我想将USDA Nutrients数据库api添加到我的网站。 I want the user to be able to search for the food,select one of the appeared results and see its' nutrition information. 我希望用户能够搜索食物,选择出现的结果之一并查看其营养信息。

How can I do this in plain JS? 如何在普通JS中做到这一点? I've created a search bar in my website and JS takes the input and requests the data from the USDA api. 我在网站上创建了一个搜索栏,JS接受了输入并从USDA api请求数据。

var apiKey = '';
var q = "eggs";

var url = "http://api.nal.usda.gov/ndb/search/?format=json&q=" + q + "&sort=n" + "&max=25" + "&offset=0" + "&api_key=" + apiKey;

var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);



xhr.onreadystatechange = function() {

  if (xhr.readyState === 4)  {
  var data = JSON.parse(this.responseText);
  document.querySelector("#usdaResults").innerHTML = data.body;
  }
};
xhr.send();

I want first to present to the user a list of the results of what they searched. 我想首先向用户提供他们搜索结果的列表。 Then after they click the food, I want to present its' nutritional information(protein etc). 然后,他们点击食物后,我要介绍其营养信息(蛋白质等)。

EDIT: When a user searches a food, I want to display the "group" , "name"and "manu" of all available results. 编辑:当用户搜索食物时,我要显示所有可用结果的“组”,“名称”和“菜单”。 At the same time,when a user wants to see the nutrition information for a specific food of those listed, I want to get its' "ndbno" number and look into the USDA database for it so I can display the data after. 同时,当用户要查看所列特定食品的营养信息时,我想获取其“ ndbno”编号并在USDA数据库中查找该编号,以便以后显示数据。 Same way as displayed in the official website: https://ndb.nal.usda.gov/ndb/search/list?SYNCHRONIZER_TOKEN=c91f87b5-59c8-47e0-b7dc-65b3c067b7ff&SYNCHRONIZER_URI=%2Fndb%2Fsearch%2Flist&qt=&qlookup=egg+potato&ds=&manu= 与官方网站上显示的方式相同: https : //ndb.nal.usda.gov/ndb/search/list?SYNCHRONIZER_TOKEN=c91f87b5-59c8-47e0-b7dc-65b3c067b7ff&SYNCHRONIZER_URI=%2Fndb%2Fsearch%2Flist&qt=+qlookup=马铃薯&DS =&马努=

EDIT2: I'm getting this error now. EDIT2:我现在收到此错误。 未定义,找到0个结果

var apiKey = '';
var q = document.getElementById('search').value;

var url = "http://api.nal.usda.gov/ndb/search/?format=json&q=" + q + "&sort=n" + "&max=25" + "&offset=0" + "&api_key=" + apiKey;

var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);

function getData() {
xhr.onreadystatechange = function () {  
    if (xhr.readyState === 4 && xhr.status === 200) {  
          console.log(xhr.responseText)
          var data = JSON.parse(this.responseText);
if (data && data.list && data.list.item) {
  var html = "";
  data.list.item.map(item => {
    let string = "<p>Name: " + item.name + " Manu: " + item.manu + " Group: " + item.group + "<p>";
    html += string;
  })
}
document.querySelector("#usdaResults").innerHTML = html;
    }
       else {  
           console.log("Error", xhr.statusText);  
        }  
    }
xhr.send();
  }

HTML: HTML:

<section class="usda"> 
        <h1>USDA Nutrients Database</h1>
        <form id="search">
            <input type="text" placeholder="Search.." name="search">
            <button type="button" onclick="getData();">Search</button>
          </form>
          <div id="usdaResults"></div>
    </section>

So, it may be that there are errors with your XHR call - however we can catch and log those errors. 因此,您的XHR调用可能存在错误-但是我们可以捕获并记录这些错误。 You want to open your developer tools in your browser (usually right click > developer tools) to look at the JS logs. 您想要在浏览器中打开开发人员工具(通常右键单击>开发人员工具)以查看JS日志。

I'm getting: VM131:20 GET http://api.nal.usda.gov/ndb/search/?format=json&q=eggs&sort=n&max=25&offset=0&api_key= 403 (Forbidden) 我正在获取: VM131:20 GET http://api.nal.usda.gov/ndb/search/?format=json&q=eggs&sort=n&max=25&offset=0&api_key= 403 (Forbidden)

But that's because I have no API Key. 但这是因为我没有API密钥。 If you do not, you'll need to get an API key from them. 如果不这样做,则需要从它们那里获取API密钥。

I have grabbed some code from another SO post, here: 我从另一个SO帖子中获取了一些代码,在这里:

var apiKey = '';
var q = "eggs";

var url = "http://api.nal.usda.gov/ndb/search/?format=json&q=" + q + "&sort=n" + "&max=25" + "&offset=0" + "&api_key=" + apiKey;

var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);



xhr.onreadystatechange = function (oEvent) {  
    if (xhr.readyState === 4) {  
        if (xhr.status === 200) {  
          console.log(xhr.responseText)  
        } else {  
           console.log("Error", xhr.statusText);  
        }  
    }  
}; 
xhr.send();

Reference: 参考:

XMLHttpRequest (Ajax) Error XMLHttpRequest(Ajax)错误

EDIT: 编辑:

For the response, once you have parsed the JSON - you can get all the available name, group and manu of the data as so - I've output the details in 对于响应,解析了JSON之后-您可以获取数据的所有可用名称,组和操作表-我将详细信息输出到

tags, and this is untested - so maybe incorrect, but this is more for pseudo code. 标记,并且未经测试-可能不正确,但这更多是针对伪代码。

var data = JSON.parse(this.responseText);
//Assuming data is valid!
if (data && data.list && data.list.item) {
  var html = "";
  data.list.item.map(item => {
    let string = "<p>Name: " + item.name + " Manu: " + item.manu + " Group: " + item.group + "<p>";
    html += string;
  })
}
document.querySelector("#usdaResults").innerHTML = html;

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

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