我正在尝试在 Spring MVC 中学习 jQuery AJAX,我正在尝试将一个值从 View 传递到 Controller ,并从 Controller 在控制台中打印该值,我想稍后学习如何在 Controller 中更改该值,然后将其传递到我的 View ,但现在我遇到了 400 错误请求。
这是我的 Controller 方法
@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),
并且我不再有400错误,我将成功 block 更改为:
`success: function(response)
{
alert( "Name: "+response);
$('#name').val('');
},`
它会在警报中打印 [object Object],在我的 Eclipse 控制台中,名称变量值为 {}
最佳答案
尝试数据:JSON.stringify(json)
。您需要先将 JavaScript 变量转换为 JSON 字符串。
关于java - 在 spring mvc 中使用 jQuery ajax 从 html 页面传递值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28462774/