Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

jquery - Populating dropdown menu with JSON Data

I'm tyring to use AJAX to populate a dropdown box based on the selection of another dropdown. I followed a tutorial using jQuery located here - http://remysharp.com/2007/01/20/auto-populating-select-boxes-using-jquery-ajax/ and have altered the select box ID names in the select box names in the script.

When there's a change to the value of the main checkbox the ajax is sent and returns as below:

{
  "1": "Kieran Hutchinson",
  "2": "Caleb Tan",
  "3": ""
}

THis is slightly different to the JSON string that is returned in the tutorials code which looks like this

[{
  optionValue: 10,
  optionDisplay: 'Remy'
}, {
  optionValue: 11,
  optionDisplay: 'Arif'
}, {
  optionValue: 12,
  optionDisplay: 'JC'
}]

I'm thinking this is the issue but I have no idea how to get the correct values out of my JSON response.

The javascript is as below:

$(function() {
  $("select#ContactCompanyId").change(function() {
    $.getJSON("contactList", {
      id: $(this).val(),
      ajax: 'true'
    }, function(j) {
      var options = '';
      for (var i = 0; i < j.length; i++) {
        options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
      }
      $("select#QuoteContactId").html(options);
    })
  })
})

Thanks in advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your problem is this line:

options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';

is expecting data sent in the format of the tutorial. Yours is a different format. Try:

options += '<option value="' + i + '">' + j[i] + '</option>';

You have the 'value' as just an index -- i, and the value as the value with that key, j[i]. so the option tag you'd end up with would look like this:

<option value="1">Kieran Hutchinson</option>

To explain more: the original data was in format like this:

// The tutorial data
array[0]['optionValue'] = 10;
array[0]['optionDisplay'] = 'Remy';

// Your data
array[1] = 'Kieran Hutchinson';

also, if that was actual data returned in your example, your iterator for (var i = 0; i < j.length; i++) will fail because you aren't starting at an index of 0. Use for(i in j) { ... }


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...