当谈到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"
}
]
你想在客户端搜索zip或发出一些网络请求? –
你可以添加一个变量来保存JSON内容并将其填充到document.ready()中吗? – g2000
@LeshaOgonkov我不确定,你有什么建议? –