首页 > 解决方案 > 无法在下拉列表 jquery 中显示 json 数据

问题描述

我从我的 php 代码中获取 json 数据,如下所示:

{2:“罗伯特”,3:“阿德姆”}

现在我想使用 jQuery 在下拉列表中显示它我正在使用以下代码,但在下拉列表中获取对象。

jQuery(response).each(function (index, value) {
  jQuery("#name").append(jQuery("<option>").val(value).text(value));
});

标签: javascriptphpjquery

解决方案


除了做JSON.parse(). .each()回调应该应用于Array不是一个Object,只需将您的响应对象转换为Arrayusing Object.values(),这是一个工作片段:

let responseStr = {2:"Robert ", 3:"Adem"}; // <----- Make sure that its an object if its not then you have to do JSON.pares().
console.log(Object.values(responseStr));
jQuery(Object.values(responseStr)).each(function(index,value){
   jQuery('#name').append(jQuery('<option>').val(value).text(value));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="name"></select>


推荐阅读