我有一个邮政编码列表,需要使用 jQuery 进行搜索。
我的 CSV 文件中有邮政编码,如下所示:
2407;ELVERUM 2425;TRYSIL 2427;TRYSIL 2446;ENGERDAL 2448;ENGERDAL
The list is pretty big, over 4000 entries, zip-code and corresponding city.
What the fastest way to search trough the list in the browser? JSON? If that's the case, how can I convert the list to JSON or another format if better?
{ "2407": "ELVERUM", "2425": "TRYSIL" }
Can someone show me the mest way to do this?
Update
Would it be possible/faster to search the loaded CSV file with just Regex?
Update2 I'm looking for an exact match, and it's only going to search when it has 4 numbers.
Update3 Here is my code:
$('#postnummer').keyup(function(e) {
if($(this).val().length == 4) {
// Code to search the JSON for an exact match.
}
});
$.getJSON("data.json",function(data){
});
谁能告诉我如何使用此代码?
最佳答案
这是一个网页,可将您的 CSV 从 URL 转换为 JSON。您可以在计算机本地使用它。使用 JQuery 和 CSV和 JSON插件。 注意:此脚本是针对给定 CSV 的快速破解。
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script src="http://js-tables.googlecode.com/svn/trunk/jquery.csv.min.js"></script>
<script src="http://jquery-json.googlecode.com/files/jquery.json-1.3.min.js"></script>
<script>
jQuery(function($){
$('#conv').click(function(){
$.get($('#myurl').val(), function(data){
var csvobj = {};
var csvray = $.csv(';')(data);
$(csvray).each(function(){
csvobj[this[0]] = this[1];
});
$('#jsondata').val( "areacodes=" + $.toJSON(csvobj) );
});
});
});
</script>
Url to CSV: <input type="text" id="myurl" value="tilbud5.csv" />
<input type="button" id="conv" value="convert url to json" />
<br/>
<textarea id="jsondata" rows="1000" cols="100"></textarea>
使用 JSON 数据,这只是一个示例:
$('#postnummer').keyup(function(e) {
if($(this).val().length == 4) {
alert(areacodes[$(this).val()]);
}
});
$.getJSON("data.json?callback=?");
关于javascript - 使用 jQuery 快速搜索邮政编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1263205/