0

I am new to jQuery. I am creating the json string in my servlet using gson-2.2.3.jar:

Gson gs = new Gson();
    String json = gs.toJson(names);
    System.out.println(json);
    PrintWriter out = resp.getWriter();
    out.println(json);
    out.close();

Below are the two commented codes I tried for binding the json string with drop-down but none of them works:

$.ajax({
         type:"POST",
         url: "DropDownController",
         success: function(result){
            alert(result);
            /* for (var id in result) {
                $("#drpDown").append('<option value="'+id+'">'+id+'</option>');
            } */
            /* $.each(result, function (index, value) {                 
                $("#drpDown").append('<option value="'+value.id+'">'+value.name+'</option>');
            }); */
         }
      });

The alert message box present in the success displays the json string in below format:

["Alabama","California","Alaska","Ohio"]

Kindly let me know how to bind the above json string data with the drop-down.

2 Answers 2

4

Try like this:

$.ajax({
    type: 'POST',
    url: 'DropDownController',
    dataType: 'json',
    success: function(result) {
        $.each(result, function() {
            $("#drpDown").append(
                $('<option/>', {
                    value: this,
                    html: this
                })
            );
        });
    }
});
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the reply, its working great. Can you please explain whats going on inside the .each? I am new to jquery and hence willing to understand it line by line. Kindly elaborate.
For each iteration of the loop the .append() method will add its argument to the dropdown as child element. The $('<option/>', { value: this, html: this }) will create a new <option> element that will get appended and safely set its inner HTML and value attribute to this. Now this inside the $.each refers to the current element that's being iterated. Since you have an array of strings ["Alabama","California","Alaska","Ohio"], then it will refer to Alabama, California, ...
why not type: 'GET',
2

Try this

var jso=["Alabama","California","Alaska","Ohio"]
for (var i in jso) {
  $("#test").append('<option value="'+jso[i]+'">'+jso[i]+'</option>');
} 

DEMO

1 Comment

Thanks for the reply, it works only if I have dataType: 'json' set inside the success block.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.