javascript - 使用 jQuery 快速搜索邮政编码

标签 javascript jquery json csv

我有一个邮政编码列表,需要使用 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 和 CSVJSON插件。 注意:此脚本是针对给定 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/

相关文章:

javascript - onmouseover 不适用于绝对位置

javascript - Javascript 窗口导航器浏览器名称在 Chrome 中不起作用

javascript - jQuery AJAX 未输入 "success"

python - 如何从 Python 中的 json 文件一起调用变量和字符串?

ios - 根据输入从服务器端检索数据

javascript - 为什么需要设置原型(prototype)构造函数?

javascript - d3 路径仅显示路径/线最多 328 个点而不是 329 个或更多

javascript - 使用 livevalidation 脚本 - 除 _(下划线)-(连字符)之外的特殊字符。 (点)和空格

jquery - 如何在 codeigniter 中制作一个简单的加一投票系统

javascript - "external"javascript函数可以调用 "jQuery functions"吗?