从json获取值并设置为select选项

时间:2018-09-02 09:36:37

标签: javascript jquery

在下面检查我的JQ代码。我有一个data变量中的json数据。而且我想循环遍历所有数据并在html中设置值,例如示例html。你能帮我解决这个问题吗?预先感谢

HTML:

<select name="mainMenuSelect" id="mainMenuSelect">
    <option value="MainMenuId">MenuName</option> //this output is my target
</select>

jQuery代码:

var data = '{"MainMenuId":6,"MenuName":"T-Shairt","StoreId":1,"Store":null},{"MainMenuId":7,"MenuName":"Pants","StoreId":1,"Store":null},{"MainMenuId":9,"MenuName":"unixx","StoreId":1,"Store":null},{"MainMenuId":10,"MenuName":"things","StoreId":1,"Store":null}';

$.each(data, function (key, value) {
    $('#mainMenuSelect').append('<option value=' + key + '>' + value + '</option>');
});

4 个答案:

答案 0 :(得分:1)

您的JSON格式无效。这是工作代码

<select name="mainMenuSelect" id="mainMenuSelect">
    <option value="MainMenuId">MenuName</option>
</select>

<script>
  var data = [{"MainMenuId":6,"MenuName":"T-Shairt","StoreId":1,"Store":null},{"MainMenuId":7,"MenuName":"Pants","StoreId":1,"Store":null},{"MainMenuId":9,"MenuName":"unixx","StoreId":1,"Store":null},{"MainMenuId":10,"MenuName":"things","StoreId":1,"Store":null}];

var i = 0;

while(i < data.length){

  document.getElementById("mainMenuSelect").innerHTML = document.getElementById("mainMenuSelect").innerHTML + "<option value='"+data[i]["MainMenuId"]+"'>"+data[i]["MenuName"]+"</option>";
  
  i++;

}

</script>

答案 1 :(得分:0)

您的JSON是一个字符串,您需要将其转换为javascript对象:

$.each(JSON.parse(data), function (key, value) {
    $('#mainMenuSelect').append('<option value=' + key + '>' + value + '</option>');
});

答案 2 :(得分:0)

您需要将数据字符串转换为有效的json,然后将其解析为对象。

您也不需要jQuery将选项添加到选择中。

var data = '{"MainMenuId":6,"MenuName":"T-Shairt","StoreId":1,"Store":null},{"MainMenuId":7,"MenuName":"Pants","StoreId":1,"Store":null},{"MainMenuId":9,"MenuName":"unixx","StoreId":1,"Store":null},{"MainMenuId":10,"MenuName":"things","StoreId":1,"Store":null}';

var options = JSON.parse('[' + data + ']');
var select = document.getElementById('mainMenuSelect');
options.forEach(function (option, i) {
  select.options[i] = new Option(option.MenuName, option.MainMenuId);
});
<select name="mainMenuSelect" id="mainMenuSelect">
</select>

答案 3 :(得分:0)

这是您的解决方案:

var data = [{"MainMenuId":6,"MenuName":"T-Shairt","StoreId":1,"Store":null},{"MainMenuId":7,"MenuName":"Pants","StoreId":1,"Store":null},{"MainMenuId":9,"MenuName":"unixx","StoreId":1,"Store":null},{"MainMenuId":10,"MenuName":"things","StoreId":1,"Store":null}]



$.each(data, function (key, value) {
   $('#mainMenuSelect').append('<option value=' + value.MainMenuId + '>' + value.MenuName + '</option>');
});

demo