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;
}
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:
This assumes the model is json
Hope this helps