1

「郵便番号」ユーザーがテキストボックスに入力した内容に基づいて、「都市」と「州」を画面に表示したいと思います。zip、市、州の3列のテキストファイルがあります。これを行うためにjavascript関数を構造化する最も効率的な方法は何ですか?

4

2 に答える 2

0

1) You need to define a server function that will return the city and state in JSON based on a zip code. 2) Subscribe to change, keyup and input events on an input field. 3) Define a JavaScript function that will call the server function using AJAX. On the success function, you set the fields using the response.

I'm pasting the client-side code below:

$("#txtZipCode").bind("change keyup input", function (e) {
        var field = $(this);
        if (field.val().length === 5) {
            showLocation(field.val());
        }
        else
            showLocation("");
    });

function showLocation(zipCodeValue) {
    var txtCity = $("#city");
    var txtState = $("#state");
    if (zipCodeValue.toString().length != 5) {
        txtCity.val("");
        txtState.val("");
    }
    else {
        $.ajax({
            dataType: "json",
            url: "Location/GetZipCode",
            data:
                {
                    zipCodeNumber: zipCodeValue
                },
            success: function (data) {
                    txtCity.val(data.City);
                    txtState.val(data.State);
            }
        });
    }
}
于 2014-06-10T18:49:05.243 に答える
0

テキスト ファイルを次の形式の JSON オブジェクトに前処理します。

{
    "10461": { City: "Bronx", State: "NY" }
    ... 
}

本当に怠け者なら、d3.nestを使ってテキスト ファイルから直接これを行うことができます。ただし、各クライアントがテキスト ファイルを読み込んで繰り返し実行するのではなく、1 回実行して JSON を保存するだけであれば、クライアントにとってはすばらしいことです。

それができたら、後は簡単です... JSON オブジェクトを読み取り、郵便番号を使用してそれにインデックスを付け、都市/州を取得するだけです。

于 2013-02-23T05:29:35.360 に答える