如何从Json对象或Array中检索数据并使用jquery更新下拉列表

时间:2013-02-25 21:37:48

标签: jquery json

我正在尝试这个很长一段时间在这里搜索不同的帖子..但是无法获得关于如何从JSON对象或数组获取数据/值的概念

我正在使用Gson将我的ArrayList转换为JSON。

response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
Gson gson=new Gson();
JsonObject myobj=new JsonObject();
JsonElement element=gson.toJsonTree(owningOrgRecords);
    myobj.add("owningorg", element);
   out.print( myobj.toString());
 //i tried this too String teamJSON=gson.toJson(owningOrgRecords); and out.print(teamJSON).

当我使用myobj.toString()

时,我得到了

JSON对象

{
"owningorg": [
    {
        "owning_org_id": 157,
        "owning_org_desc": "FirstOwning Org",
        "team": "SSSB Team",
        "created_on": "TodayDate",
        "created_by": "Adminuser"
    },
    {
        "owning_org_id": 158,
        "owning_org_desc": "SecondOwning Org",
        "team": "SSSB Team",
        "created_on": "TodayDate",
        "created_by": "Adminuser"
    },
    {
        "owning_org_id": 159,
        "owning_org_desc": "ThirdOwning Org",
        "team": "SSSB Team",
        "created_on": "TodayDate",
        "created_by": "Adminuser"
    }
]

}

JSON数组

[
{
    "owning_org_id": 157,
    "owning_org_desc": "FirstOwning Org",
    "team": "SSSB Team",
    "created_on": "TodayDate",
    "created_by": "Adminuser"
},
{
    "owning_org_id": 158,
    "owning_org_desc": "SecondOwning Org",
    "team": "SSSB Team",
    "created_on": "TodayDate",
    "created_by": "Adminuser"
},
{
    "owning_org_id": 159,
    "owning_org_desc": "ThirdOwning Org",
    "team": "SSSB Team",
    "created_on": "TodayDate",
    "created_by": "Adminuser"
}

我目前拥有的Java脚本。

    $.ajax({
        type:"POST",
        dataType:"json",
        url:"myServlet",
        cache:false,
        data:a,
        success:function(html){
            console.debug(html);
            var jsonList=html.owningorg;
            alert(jsonList.owningorg.lenght);
            $("#owningorg").removeAttr("disabled");
            $("#owningorg").html("");
        for(var i=0;i<jsonList.lenght;i++){

            listItems+="<option value='" + jsonList.owningorg[i].owning_org_id + "'>" + jsonList.owningorg[i].owning_org_dec[i] + "</option>";

            } 



        }
    }); 

我的问题是如何使用Jquery将owning_org_dec和Owning_org_id填充到drop和desc中。我目前在下拉列表中获得空值。请解释我如何从JSON对象和JSON阵列中检索数据到下拉列表或指向帖子或教程。谢谢你的时间。

1 个答案:

答案 0 :(得分:0)

类似的东西:

var thisVal = jsonList.owningorg[i].owning_org_id;
var thisTxt = jsonList.owningorg[i].owning_org_dec[i];
$("<option />").attr("value", yourvalue).text(thisTxt).appendTo("#NAMEofSelect");

请记住,您必须传递要附加的选择字段的名称。 (#NameofSelect)