Michael
Michael

Reputation: 2128

Access model object with JSTL

I'm currently trying to get to grips with AJAX, and have a problem accessing the model object.

What my test code does is get the value of the selected from a drop down list, when the button is pressed it passes this value to AjaxTest(), which attaches the param to the model, but I can't get seem to output the model object - I was wondering why this might be?

There is definitely a value for param.

<div id="result"></div>

<script type="text/javascript">

    var param = document.getElementById("blah").value;

    var loadUrl = "/ajax/" + param;  
    $("#button").click(function(){  

        $.post(loadUrl, function(data){
            alert("Data Loaded: " + data);
            $("#result").html("<p>Param: ${output}</p>"); 
        });
    });  
</script>


@RequestMapping(value = "/ajax/{param}", method = RequestMethod.POST)
public @ResponseBody String AjaxTest(@PathVariable String param, final ModelMap model){

    model.addAttribute("output", param);
    return param;
}

Upvotes: 0

Views: 1419

Answers (2)

JB Nizet
JB Nizet

Reputation: 691695

When page is first loaded, the JSP code executes. This code contains the following lines:

$("#button").click(function(){  

    $.post(loadUrl, function(data){
        alert("Data Loaded: " + data);
        $("#result").html("<p>Param: ${output}</p>"); 
    });
});

So, the JSP EL code is interpreted by the container, and ${output} is replaced by the value of the output attribute. Since this attribute is null, the following HTML code is generated and sent to the browser:

$("#button").click(function(){  

    $.post(loadUrl, function(data){
        alert("Data Loaded: " + data);
        $("#result").html("<p>Param: </p>"); 
    });
});

When you click on the button, the above JavaScript code executes. It sends an AJAX request to the ajax URL, and when the response comes back, it executes the callback function:

alert("Data Loaded: " + data);
$("#result").html("<p>Param: </p>");

So, the data received from the server is displayed in an alert box, and then the content of the HTML element identified by "result" is replaced by <p>Param: </p>.

Upvotes: 1

Nathan Russell
Nathan Russell

Reputation: 3668

I think you are getting a bit mixed up with what is client side and server side. You java looks correct, but your js is trying to access a jstl expression ( ${output} ). The jstl expression won't resolve when the page is rendered, which will be before the Ajax request/response has happened.

Your js needs to work with the variable 'data' which is the data that your java adds to the model. Something like this:

$("#result).html("<p>Param: " + data.output + "</p>");

This assumes the model is json Hope this helps

Upvotes: 2

Related Questions