![](/img/trans.png)
[英]Passing a list of strings in a Spring MVC controller using Jquery Ajax
[英]passing a value from a html page using jQuery ajax in spring mvc
我正在尝试在Spring MVC中学习jQuery AJAX,并且试图将一个值从视图传递给控制器,并从该控制器在控制台中打印该值,我想稍后学习如何在控制器中更改该值并然后将其传递给我的视图,但现在我有一个400错误的请求。
这是我的控制器方法
@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;
}
这是我的页面formNormal.html
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></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>
编辑**我将数据更改为data: JSON.stringify(json),
并且我不再data: JSON.stringify(json),
400错误,我将成功块更改为:
`success: function(response)
{
alert( "Name: "+response);
$('#name').val('');
},`
并在警报中向我显示[object Object],并且在我的Eclipse控制台中,名称变量的值为{}
尝试data: JSON.stringify(json)
。 您需要先将javascript变量转换为JSON字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.