Luca Sepe Luca Sepe - 2 years ago 174
Javascript Question

Use Spring Model attribute to set js variable

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 variabiles 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 variabiles
    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? Wiche difference there is between this 2 approachs?

  2. In the ajax function, when I have
    success: function()
    , wich 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
    ?


Answer Source

You can use Model object and use addAttribute method for every object you need to have in ajax success function. In every Spring method you can add Model object, for example:

@RequestMapping(value="value", method = RequestMethod.POST)
    public @ResponseBody String yourMethod(@RequestParam(value="yourParam") String yourParam,
                       Model model){
    String a = "Your String";
    int b = 456;

    model.addAttribute("myString", a);
    model.addAttribute("myInt", b);

    return "";
}

The success function must be declared with one parameter, that is the response. Inside this parameter you will find the parameters you added in model object (myString and myInt):

success: function(response){   
            // response.myString will be "Your String"
            // response.myInt will be 456
        }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download