java 如何在 Spring MVC 的控制器中操作 jQuery AJAX JSON 数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28480258/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to manipulate jQuery AJAX JSON data in a controller in spring MVC
提问by stackUser2000
How many ways are to pass JSON data to a spring controller?
有多少种方法可以将 JSON 数据传递给 spring 控制器?
I followed this tutorialand they pass the data using the following syntax:
我遵循了本教程,他们使用以下语法传递数据:
data: "{\"name\":\"hmkcode\",\"id\":2}",
This works but since I need to retrieve the data from a user using a text input I don't know how to put my variable in that string.
这有效,但由于我需要使用文本输入从用户那里检索数据,因此我不知道如何将我的变量放入该字符串中。
I tried doing using the following syntax:
我尝试使用以下语法:
data: "{\"name\":\name\}"
But it returns the following error:
但它返回以下错误:
status: parsererror er:SyntaxError: Unexpected tokken a
状态:解析器错误 er:SyntaxError:意外标记 a
I have seen other sites that uses the following syntax:
我见过使用以下语法的其他网站:
data: {"name":name}
But that gives me the same error.
但这给了我同样的错误。
This works but I don't know if is the best approach.
这有效,但我不知道是否是最好的方法。
var json = {"name" : name};
...
data: JSON.stringify(json),
I manage to pass the JSON string to one of my controllers but I get the string like this:
我设法将 JSON 字符串传递给我的一个控制器,但我得到这样的字符串:
{"name": Joe, "lastname": Smith}
Is there a way to only get that info in a Person Object or at least get only Joe in a string and Smith in another one?
有没有办法只在 Person 对象中获取该信息,或者至少只在字符串中获取 Joe 和在另一个字符串中获取 Smith?
<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 lastname = $('#lastname').val();
var json = {"name" : name, "lastname" : lastname};
//console.log(json);
$.ajax(
{
type: "POST",
url: "formShow",
data: JSON.stringify(json),
//data: "{\"name\":name}",
//data: {"name":name},
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
beforeSend: function(xhr)
{
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success: function(data)
{
//console.log(data);
console.log(data.name);
//var data = $.parseJSON(JSON.stringify(response));
//alert(data);
alert( "name: "+data.name);
//$('#name').val('');
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
}
/* 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" id="name" name="name">
<br>
Last Name in view: <input type="text" id="lastname" name="lastname">
<br>
Show modify name in view: <input type="text" id="modifyname" name=""modifyname"">
<br>
<input type="button" value="Add Users" onclick="doAjaxPost()">
</fieldset>
<br>
And these are my controllers:
这些是我的控制器:
@RequestMapping(value = "formShow", method = RequestMethod.GET)
public String formularioIncidencia (Model model) {
return "formShow";
}
@RequestMapping(value = "formShow", method = RequestMethod.POST)
public @ResponseBody String getTags(@RequestBody String name)
{
String variableAjax= name;
System.out.println("controller variable is " + variableAjax);
//that prints me this "{name: Joe, lastname: Smith}"
return variableAjax;
}
EDITED**** this is my User class
已编辑**** 这是我的用户类
public class Userimplements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private String lastname;
public User(){}
}
I edited my controllers to the following
我将控制器编辑为以下内容
@RequestMapping(value = "formShow", method = RequestMethod.GET)
public String formShow(Model model) {
return "formShow";
}
@RequestMapping(value = "formShow", method = RequestMethod.POST)
public @ResponseBody User getTags(@RequestBody final User user, Model model)
{
//what should i do here parse my user to JSON how??
user.setName("name changed");
model.("modifyname", user.getName() );
return User;
}
回答by Sandeep Patange
From Ajax you can also pass data as data:'name='+ name+'&lastname='+ lastname,
And at controller end you can make use of @RequestParam
annotation to get this value passed from ajax call.
Ajax code looks as follows:
从 Ajax 中,您还可以将数据作为传递,data:'name='+ name+'&lastname='+ lastname,
并且在控制器端,您可以使用@RequestParam
注释来获取从 ajax 调用传递的值。Ajax 代码如下所示:
$.ajax({
type: 'POST',
url:'your controller url',
data:'name='+ name+'&lastname='+ lastname,
success: function(msg){
alert('wow' + msg);
}
});
Controller code:
控制器代码:
@RequestMapping(value = "formShow", method = RequestMethod.POST)
public String getTags(@RequestParam("name") String name, RequestParam("lastname") String lastname)
{
System.out.println("name: " + name+ " lastname: "+lastname);
String fullName = name + lastname;
return fullName;
}
Hope this helped you. Cheers:)
希望这对你有帮助。干杯:)
回答by minion
- For sending the input data to controller, you don't have to necessarily use json as a format. You can simply pass them as request param and extract it on controller using @RequestParam annotation. If you want to post json data you can use JSON.stringify(json). if you to bind object to your model object, try using @Modelattribute on controller and pass the data in your ajax post. There are plenty of examples for this.
- Use @RequestParam or @RequestBody to get your data on your controller based on what approach you choose based on point 1.
- Use @ResponseBody to send the data back and if you send json data back, use Json.parseJson to convert to js object or if you send a Map, you would get a JS object back in your ajax handler. You can use Dot notation to populate the data.
- 要将输入数据发送到控制器,您不必一定使用 json 作为格式。您可以简单地将它们作为请求参数传递并使用 @RequestParam 注释在控制器上提取它。如果你想发布 json 数据,你可以使用 JSON.stringify(json)。如果要将对象绑定到模型对象,请尝试在控制器上使用 @Modelattribute 并在 ajax 帖子中传递数据。这方面有很多例子。
- 根据您根据第 1 点选择的方法,使用 @RequestParam 或 @RequestBody 在您的控制器上获取您的数据。
- 使用@ResponseBody 发回数据,如果你发回 json 数据,使用 Json.parseJson 转换为 js 对象,或者如果你发送一个 Map,你会在你的 ajax 处理程序中得到一个 JS 对象。您可以使用点表示法来填充数据。
回答by Celeb
A few observations will be enlighten ( i hope ).
一些观察会有所启发(我希望)。
In JAVA: it is always better to specify your "request" object and your response object like this:
在 JAVA 中:最好像这样指定“请求”对象和响应对象:
@RequestMapping(method = RequestMethod.POST, value = "/rest/path/to/action",
consumes = "application/json", produces = "application/json")
@ResponseStatus(value = HttpStatus.OK)
public @ResponseBody
List<?> action(@RequestBody List<?> requestParam) {
List<String> myret = new ArrayList<String>();
for (int i=0; i < requestParam.size() ;i++){
myret.add(requestParam.get(i).toString());
}
}
}
In this case i defined the same object "List" as my request and my response object, but that it's up to your definitions. If you want to represent a user object, you must define your user object and specify the fields u want with Hymanson lib. It is a little tricky, but once you got it, you can pass any object you want.
在这种情况下,我定义了与我的请求和响应对象相同的对象“列表”,但这取决于您的定义。如果你想代表一个用户对象,你必须定义你的用户对象并用 Hymanson lib 指定你想要的字段。这有点棘手,但是一旦你掌握了它,你就可以传递任何你想要的对象。
And then you can just pass your data in AJAX as defined in your controller. So in this case would be:
然后您可以按照控制器中的定义在 AJAX 中传递您的数据。所以在这种情况下将是:
var postData = ["Somedata", "Someotherdata"];
$.ajax(
{
type: "POST",
url: "/rest/path/to/action",
data: postData, // i can do this, because it is defined this way in my controller
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
//etc etc
I hope it helps :)
我希望它有帮助:)
Cheers
干杯