根据收到的输入从JSON获取数据

时间:2016-03-25 17:59:47

标签: javascript json

我需要根据收到的输入获取数据。

例如,如果输入是'Royal python',我应该获得Royal python的详细信息。但是使用以下代码,我得到错误,说'你要求的文件不存在'。但我得到了fname的价值。但不确定函数是否正确从数组中获取数据。同时我想知道是否有更短的方法来执行此操作。请帮忙?

我正在使用JavaScript,我的代码和网页外观如下:

<!DOCTYPE html> 
<html> 
<body>  

<form> <input type="text" name="fname" required> 
<button onclick="myFunction()">OK</button> `enter code here`
</form>  
<p id="demo"></p>  
<script> var text = '{"animals":[' + 
'{"Common Name":"Royal Python","Order":"Squamata","Family":"Boidae","Genus":"Python","Species":"regius","Zoo":"Blackpool Zoo","Number":4 },' + 
'{"Common Name":"Emperor Penguin","Order":"Sphenisciformes","Family":"Spheniscidae","Genus":"Aptenodytes","Species":"forsteri",`   "Zoo":"Welsh Mountain Zoo","Number":35 },' +` 
'{"Common Name":"Chimpanzee","Order":"Primates","Family":"Pongidae","Genus":"Pan","Species":"troglodytes",    "Zoo":"Blackpool Zoo","Number":8 }]}';  

obj = JSON.parse(text);  


//function to fetch data based on input

function myFunction(fname) 
{ var ani = ""; 
if (document.getElementByname("fname")="Royal Python")   
var ani =  document.getElementById("demo").innerHTML = obj.animals[0].Zoo + " " + obj.animals[0].Species; }}  </body> </html>

2 个答案:

答案 0 :(得分:0)

您的代码中存在许多问题:

document.getElementByname("fname")="Royal Python"应为document.getElementsByName("fname")[0].value == "Royal Python"

此外,编写文本字符串然后将其解析为JSON很麻烦。只需使用JavaScript对象。

在尝试确定动物时,你自己也很难。如果您的浏览器支持,请使用Array.findIndex()

这是一个有效的例子:

&#13;
&#13;
var obj = {animals:[{CommonName:"Royal Python",Order:"Squamata",Family:"Boidae",Genus:"Python",Species:"regius",Zoo:"Blackpool Zoo",Number:4 }, {CommonName:"Emperor Penguin",Order:"Sphenisciformes",Family:"Spheniscidae",Genus:"Aptenodytes",Species:"forsteri",Zoo:"Welsh Mountain Zoo",Number:35 }, {CommonName:"Chimpanzee",Order:"Primates",Family:"Pongidae",Genus:"Pan",Species:"troglodytes",    Zoo:"Blackpool Zoo",Number:8 }]};

//function to fetch data based on input
function myFunction() { 
  var name = document.getElementsByName("fname")[0].value;
  var index = obj.animals.findIndex(function(item) {
    return item.CommonName === name;
  });
  if (index >= 0) {
    document.getElementById("demo").innerHTML = obj.animals[index].Zoo + " " + obj.animals[index].Species;
  }
}
&#13;
<input type="text" name="fname" required value="Royal Python"> 
<button onclick="myFunction()">OK</button>
<p id="demo"></p>  
&#13;
&#13;
&#13;

答案 1 :(得分:0)

以下是您的问题的解决方案,该问题使用for循环来检查动物数组的每个索引以进行匹配。此匹配也不区分大小写。

<!DOCTYPE html>
<html>

<body>
    <p id="demo"></p>
    <input type="text" name="fname" required>
    <button onclick="fetchAnimal()">OK</button> `enter code here`
    <script>
    var animalsArr = [{
        "commonName": "Royal Python",
        "order": "Squamata",
        "family": "Boidae",
        "genus": "Python",
        "species": "regius",
        "zoo": "Blackpool Zoo",
        "number": 4
    }, {
        "commonName": "Emperor Penguin",
        "order": "Sphenisciformes",
        "family": "Spheniscidae",
        "genus": "Aptenodytes",
        "species": "forsteri",
        "zoo": "Welsh Mountain Zoo",
        "number": 35
    }, {
        "commonName": "Chimpanzee",
        "order": "Primates",
        "family": "Pongidae",
        "genus": "Pan",
        "species": "troglodytes",
        "zoo": "Blackpool Zoo",
        "number": 8
    }]

    function fetchAnimal() {
        var i;
        var len = animalsArr.length;
      
        // convert input name to lower-case
        var name = document.getElementsByName('fname')[0].value.toLowerCase();

        for (i = 0; i < len; i++) {
            // check to see if lower-case input is the same as lower-case animal name (this ensures the match is case-insensitive)
            if (animalsArr[i].commonName.toLowerCase() === name) {
                document.getElementById('demo').innerHTML = animalsArr[i].zoo + ' ' + animalsArr[i].species;
            }
        }
    }
    </script>
</body>

</html>

注意:如果您打算为页面添加更多交互性,强烈建议将JS代码移动到外部脚本文件中。