當談到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我不確定,你有什麼建議? –