Use Spring Model attribute to set js variable

Viewed 1554

I'm Using Spring Boot and there is a point that I don't understand. Suppose I have a model, created in a Controller's method, annotated with @ResponseBody annotation. I must put, inside this model, 2 variables, a String and an int, that I have to use to set 2 global variables in a js file; this setting is done in case of ajax function success.

So, for semplicity, let's assume that my global variables are global1 and global2; and that the variables to put inside model are String a and int b; in this scenario, what must happend is:

$.ajax({
        ...<url, method and other actions here>...
        success: function(){
                 global1 = String a;
                 global2 = int b;
        }

My doubt are 3:

  1. How I may put the variables String a and int b inside the model? Should I use model.addObject() or it's better create a Modelmap object, fill this one with a and b and then put him inside the model? Which difference there is between this 2 approaches?

  2. In the ajax function, when I have success: function(), which parameters should I give in input to function()?

  3. Inside the success function, how can I use the model data to set the global variables? What syntax may I use to perform this? In other words, when I have my model, how can I access its variables and use to perform global1 = String a and global2 = int b?

2 Answers
Related