不能在下拉列表中显示json数据 jquery

问题描述 投票:0回答:1

我从我的php代码中得到的json数据是这样的。

{2: "Robert", 3: "Adem"}。

现在我想在下拉列表中使用jQuery来显示它,我使用下面的代码,但是在下拉列表中得到了对象,我从我的php代码中得到的json数据是这样的:{2: "Robert", 3: "Adem"}。

jQuery(response).each(function (index, value) {
  jQuery("#name").append(jQuery("<option>").val(value).text(value));
});
php jquery
1个回答
1
投票

除了做 JSON.parse(). .each() 回调应该应用在 Array 不是 Object,只要将你的响应对象转换为 Array 使用 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>

0
投票

你需要使用 $.parseJSON() 和检索数据。

如果你想不进行解析,请参考下面的方法。

如何访问JSON对象namevalue?


0
投票

如果从PHP文件中得到的响应是一个JSON字符串,那么你必须将它转换为一个javascript数组,然后迭代它以得到你的选项。

使用 JSON.parse();

var options = JSON.parse(JSON.stringify(response));

jQuery.each( options, function( index, value ) {
   $('#name').append('<option value="'+index+'">'+value+'</option>');
});
© www.soinside.com 2019 - 2024. All rights reserved.