2

I am trying to dynamically generate a list/dropdown using JQuery's .ajax method. Following is the code I wrote:

<script type="text/javascript">
    $(document).ready(function() {
        alert('in doc');
        $.ajax({
            url: "dyn/list",
            type: "GET",
            data: "list="+'',
            dataType: "json",
            error: function() {alert('eerrrr');},
            success: function(data) {
                alert('success');
                alert(data);
                    $('#seltag').append(
                        $('<option></option>').html(data)
                    );
            },
            complete: function() {}
        });
        });</script>

And my corresponding controller method looks like

    @RequestMapping(value = "/dyn/list", method = RequestMethod.GET)
public @ResponseBody String getList(@RequestParam String list)
{
    ArrayList<String> newList = new ArrayList<String>();
    newList.add(opt0);
    newList.add(opt1);
    newList.add(opt2);
    return(new JSONArray(newList).toString());
    //return opt0;
}

Where opt0,1 and 2 are static string variables. Each time an error is returned. I have also tried .getJSON but to no avail. Help me out fellas!!

1
  • "Each time an error is returned." Help us out and tell us what that error is, that's going to make it considerably easier for us to help you. Commented Aug 12, 2012 at 20:38

2 Answers 2

8

You don't need to convert to JSON yourself. Spring 3 with <mvc:annotation-driven enabled and jackson in the classpath does it for you:

@RequestMapping(value = "/dyn/list", method = RequestMethod.GET)
public @ResponseBody List<String> getList(@RequestParam String list) {
    List<String> newList = new ArrayList<String>();
    newList.add(opt0);
    newList.add(opt1);
    newList.add(opt2);
    return newList;
}

For more info check out this post

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks.. it worked fine. I am actually new to web development. So excuse me for incomplete info
2

adding to oris answer, you need not do a getJSON too. Inside your success callback iterate throw the list a get the messages.

success: function(data) {
for(var count=0; count<data.length; count++){
 yourMessage = data[count];
}
//your code
}

Comments

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.