2015-09-14 69 views
0

当谈到JavaScript时,我是一个noob,但我一直在试图弄清楚这个问题。任何帮助将不胜感激。示例和教程网站也会提供帮助。我的问题是,如何将此搜索功能合并到搜索带有邮政编码的JSON文件,并返回带有该zip的数组以及与之相关的其他数据。对不起,如果这似乎没有做任何研究,相信我我一直在玩这个太久,我只需要一些方向让我开始。提前致谢。如何根据搜索值从JavaScript数组中获取值?

所以我有这样的形式:

<form> 
     <input type="text" name="zip" id="zip" placeholder="Zip Code"> 
     <button onclick="getZip(event);">Check</button> 
</form> 

的JavaScript:

<script> 
function getZip(e){ 
e.preventDefault(); 
var zip = document.getElementById('zip').value; // Gets the value from the text field "zip" on the form. 
    if (zip === "") { // Checks if the text field "zip" is empty, if so it returns an error message. 
     alert ('Please enter a zip code!'); 
    } 
    else if (zip.length > 5) { 
     alert ("Please enter a valid 5 digit numeric zip code."); 
    } 

    else if (isNaN(zip)) { // Checks if the text field "zip" for alphabetic characters. The "isNaN" function is to determine if a value does not convert to a number, if so it returns an error message. 
     alert("Please enter a numeric value."); 

    } else if (zip.length == 5) { 
     alert("Success! " + zip); 

    } else { // Returns value from the text field "zip" on the form. 
     alert(zip); 
    } 

    return false; 
} 

</script> 

JSON实例:

[ { 
    "ZipCode": 48650, 
    "City": "Pinconning", 
    "State": "Michigan", 
    "StateAbbreviation": "MI", 
    "County": "Bay" 
}, 
{ 
    "ZipCode": 48651, 
    "City": "Prudenville", 
    "State": "Michigan", 
    "StateAbbreviation": "MI", 
    "County": "Roscommon" 
    } 
] 
+0

你想在客户端搜索zip或发出一些网络请求? –

+0

你可以添加一个变量来保存JSON内容并将其填充到document.ready()中吗? – g2000

+0

@LeshaOgonkov我不确定,你有什么建议? –

回答

0

你最好的选择是使用loadash。如果JSON位于服务器端,那么您可以使用服务器端语言来解析json和筛选结果。

它可以使用lodash如果服务器端代码的NodeJS

如果客户端然后根据需要将JSON转换为使用JSON.parse和javascript对象使用loadash的地图的方法来提取数据来完成。

+0

@DallasClymer - 您是否尝试过使用lodash我在这里陈述的解决方案?这有帮助吗? –