最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Ajax add option to select for each json array - Stack Overflow

programmeradmin1浏览0评论

I need to populate a select item with the values that I get from an ajax call, I return such values as a json array. With the code below, the select is created without any options.

$.ajax({
  type: "GET",
  url: "/wp-content/gta/search_airport.php",
  data: {city: t_city}
}).done(function(resp){
  var sel = $('<select name="airport" id="slt">').appendTo('#pick_type');
  $.each(resp, function() {
$.each(this, function(k, v) {
$('<option>').val(k).text(v).appendTo('#slt');
   });
  });
});

Example json array

[{"name":"Los Angeles","code":"LAX"},{"name":"San Francisco","code":"SFO"}]

I would like the options to be something like <option value="LAX">Los Angeles</option>

I need to populate a select item with the values that I get from an ajax call, I return such values as a json array. With the code below, the select is created without any options.

$.ajax({
  type: "GET",
  url: "/wp-content/gta/search_airport.php",
  data: {city: t_city}
}).done(function(resp){
  var sel = $('<select name="airport" id="slt">').appendTo('#pick_type');
  $.each(resp, function() {
$.each(this, function(k, v) {
$('<option>').val(k).text(v).appendTo('#slt');
   });
  });
});

Example json array

[{"name":"Los Angeles","code":"LAX"},{"name":"San Francisco","code":"SFO"}]

I would like the options to be something like <option value="LAX">Los Angeles</option>

Share Improve this question asked Jan 6, 2014 at 1:26 enriqg9enriqg9 1,5071 gold badge22 silver badges42 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

You don't needed a nested $.each(). Just loop through the array and directly access the properties of the object at each index:

$.each(resp, function(k, v) {
    $('<option>').val(v.code).text(v.name).appendTo('#slt');
});

On the first iteration, v will be {"name":"Los Angeles","code":"LAX"}, so v.code will be "LAX". On the second iteration, v will be {"name":"San Francisco","code":"SFO"}, so v.code will be "SFO"...

(You may also need to add dataType:"json" to your $.ajax() options - if you don't specify jQuery tries to work it out from the response's MIME type.)

Try this,

$.ajax({
    type: "GET",
    url: "/wp-content/gta/search_airport.php",
    data: {city: t_city},
    dataType:"json"
}).done(function(resp) {
    var sel = $('<select name="airport" id="slt">').appendTo('#pick_type');
    $.each(resp, function(key,val) {
        $.each(val, function(k, v) {
            $('<option>').val(k).text(v).appendTo('#slt');
        });
    });
});
发布评论

评论列表(0)

  1. 暂无评论