状态列表json数据进入下拉列表选择使用jquery

时间:2012-02-17 15:58:22

标签: jquery json jsonp getjson

这是返回的json数据:

({"Data":{"Alabama":"AL","Alaska":"AK","Arizona":"AZ","Arkansas":"AR","California":"CA","Colorado":"CO","Connecticutt":"CT","Delaware":"DE","Florida":"FL","Georgia":"GA","Hawaii":"HI","Idaho":"ID","Illinois":"IL","Indiana":"IN","Iowa":"IA","Kansas":"KS","Kentucky":"KY","Louisiana":"LA","Maine":"ME","Massachusetts":"MA","Michigan":"MI"}})

我需要将其放入下拉选择。

$.getJSON(url + 'GetStateList?jsoncallback=?',
    function (json) {
        if (!jQuery.isEmptyObject(json.Data)) {
            //need to write logic
        }
    });

任何人都可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:3)

var data = 'jsonstring', i, select = $('select');

for(i in data){

    select.append($('<option value="' + data[i][1] + '">' + data[i][0] + '</option>'));

}

答案 1 :(得分:2)

这只是一个基本的例子,请随意使用它作为起点:

<HTML>
<HEAD>
    <TITLE>Test Example</TITLE>
</HEAD>
<BODY>
    <form>
        <select id="sel" />

    <script>
    function fill() {
        var obj = ({"Data":{"Alabama":"AL","Alaska":"AK","Arizona":"AZ","Arkansas":"AR","California":"CA","Colorado":"CO","Connecticutt":"CT","Delaware":"DE","Florida":"FL","Georgia":"GA","Hawaii":"HI","Idaho":"ID","Illinois":"IL","Indiana":"IN","Iowa":"IA","Kansas":"KS","Kentucky":"KY","Louisiana":"LA","Maine":"ME","Massachusetts":"MA","Michigan":"MI"}});
        var s = document.getElementById('sel');
        var i = 0;
        for(var propertyName in obj.Data) {
        sel.options[i++] = new Option(propertyName, obj.Data[propertyName], true, false);
    }
    }

    fill();
    </script>
    </form>
</BODY>
</HTML>