绑定JSON数组以选择 [英] Bind JSON Array to select

查看:72
本文介绍了绑定JSON数组以选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将Ajax调用的结果的JSON数组绑定到<select/>元素.

I am trying to bind a JSON array, which is the result of an Ajax call, to a <select/> element.

下面是JSON结构的示例:

A sample of the JSON structure is seen below:

[{"JD_No":1,"JD_Name":"Network Administrator"}, {"JD_No":2,"JD_Name":"System Administrator"}]

我需要实现的是提取每个元素的JD_No值和JD_Name值,并将它们绑定到html <select/>

What I need to achieve is to extract the JD_No value and JD_Name value of each element and bind them to a html <select/>

我还必须声明JSON密钥是动态的,因此无法引用特定的密钥名称.

I must also state that the JSON Key is dynamic, so referencing a specific Key Name will not be possible.

请帮忙吗?

推荐答案

如果我正确理解,您想将动态属性绑定到选择项吗?如果可以假设将始终以特定顺序返回带有特定数量的属性的对象列表,则可以基于它们的INDEX访问这些属性.

If I understand correctly, you want to bind dynamic properties to the select? If you can assume that the list of objects will always be returned with a specific amount of properties in a specific order, you can access the properties based on their INDEX.

以下示例从对象获取键和值:

The following example gets a key and value from an object:

for (var i in myArray) {
    var obj = myArray[i];
    var index = 0;
    var key, val;
    for (var prop in obj) {
        switch (index++) {
            case 0:
                key = obj[prop];
                break;
            case 1:
                val = obj[prop];
                break;
            default:
                break;
        }
    }
    $("select").append("<option value=\"" + key + "\">" + val + "</option>");
}

这篇关于绑定JSON数组以选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆