Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

jquery fill dropdown with json data

I have the following jQuery code. I am able to get the following data from server [{"value":"1","label":"xyz"}, {"value":"2","label":"abc"}]. How do I iterate over this and fill a select box with id=combobox

$.ajax({
    type: 'POST',
    url: "<s:url value="/ajaxMethod.action"/>",
    data:$("#locid").serialize(),
    success: function(data) {
        alert(data.msg);

                //NEED TO ITERATE data.msg AND FILL A DROP DOWN
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert(textStatus);
    },
    dataType: "json"
});

Also what is the difference between using .ajax and $.getJSON.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

This should do the trick:

$($.parseJSON(data.msg)).map(function () {
    return $('<option>').val(this.value).text(this.label);
}).appendTo('#combobox');

Here's the distinction between ajax and getJSON (from the jQuery documentation):

[getJSON] is a shorthand Ajax function, which is equivalent to:

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback
});

EDIT: To be clear, part of the problem was that the server's response was returning a json object that looked like this:

{
    "msg": '[{"value":"1","label":"xyz"}, {"value":"2","label":"abc"}]'
}

...So that msg property needed to be parsed manually using $.parseJSON().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...