i'm trying to learn jQuery AJAX in spring MVC and i'm trying to pass a value from a view to a controller and print that value in console from the controller, i would like later learn how to change that value in my controller and then pass it to my view but right now i'm having a 400 Bad Request.
this is my controller methods
@RequestMapping(value = "formNormal", method = RequestMethod.GET)
public String formNormal(Model model) {
return "formNormal";
}
@RequestMapping(value = "formNormal", method = RequestMethod.POST)
public @ResponseBody String jsonMethod(@RequestBody String name) {
String controllerVariable = name;
System.out.println("controller variable value is " + controllerVariable);
return controllerVariable;
}
and this is my page formNormal.html
<script src="http://ift.tt/KA8c68"></script>
<script type="text/javascript">
function doAjaxPost()
{
// get the form values
var name = $('#name').val();
var json = {"name" : name};
$.ajax(
{
type: "POST",
url: "formNormal",
data: JSON.stringify(json),
cache: false,
beforeSend: function(xhr)
{
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success: function(response)
{
alert(response);
$('#name').val('');
},
error: function (xhr, ajaxOptions, thrownError)
{
alert(xhr.status);
alert(xhr.responseText);
alert(thrownError);
}
});
}
</script>
<fieldset>
<legend>Name in view</legend>
Name in view: <input type="text" name="name">
<br>
<input type="button" value="Add Users" onclick="doAjaxPost()">
</fieldset>
<br>
EDITED** i change the data to data: JSON.stringify(json), and i no longer have the 400 error, i change to the success block to:
`success: function(response)
{
alert( "Name: "+response);
$('#name').val('');
},`
and it prints me [object Object] in the alert, and in my eclipse console the name variable value is {}
Aucun commentaire:
Enregistrer un commentaire