1

I am working on a Spring-MVC application in which I want to send different types of java.util.List to the AJAX method. I don't know if we can use model.addAttribute in the controller when giving data to AJAX method.

Situation is :

@RequestMapping(value=/mappingurl)
public @ResponseBody void sendDataToAjax(){
    List<Item1> item1;
    List<Item2> item2;
    List<Item3> item3;

    model.addAttribute("item1collection",item1);
    model.addAttribute("item2collection",item2);
    model.addAttribute("item3collection",item3);    
}

Will this work when it is an AJAX method, if not, what can I do so I can send List of objects and access it inside AJAX method. I hope my question is clear, if not, please let me know, I will improvise. Thanks. :-)

1
  • What's you AJAX method on the client side consuming? You need to return (a JSON for instance) and should be able to parse/consume it in the client side when the AJAX call finalizes Commented Apr 21, 2015 at 15:38

2 Answers 2

3

You won't have any problem adding several attributes to your model. When you return to client side you will be able to get them in an AJAX request.

Problem here is you can't use java.util.List objects by javascript at client-side, so you must create Json objects or convert to array the java.util.List.

The only thing i would change in your code is to add a response to catch succes or fail of the method:

public @ResponseBody String sendDataToAjax(){
    // do your stuff and return "KO" if something goes wrong


    return "OK"; // if success
}

This could be better done by implementing an enum class... but this is a faster way

After this, you can catch inside the ajax request the result of the server-side operatiion and continue in according to it.

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

3 Comments

So I can use the above code to send data to an Ajax method, correct? The next answer by @San Krish says no. Yes, I cannot access lists in Client-side, I guess only option is to convert to array or JsonList.
you can use to send various data objects, but no List, as @San correctly said...
Cool. Thanks. I will then use Array or JsonList. Just one thing, I know how to iterate through an array or convert list to array, but some other user in future might now, if you can write some pseudo code for future users.
1

IMHO answer is no , you can't iterate or print the Arraylist inside the AJAX response.

You can instead convert it into JSON-array and iterate it in the ajax response. A nice startup example,

Converting a Java ArrayList of strings to a JavaScript array

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.