2015-09-14 71 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我在這裏陳述的解決方案?這有幫助嗎? –