简体   繁体   English

如何在Spring MVC中的控制器中操作jQuery AJAX JSON数据

[英]How to manipulate jQuery AJAX JSON data in a controller in spring MVC

How many ways are to pass JSON data to a spring controller? 有几种方法可以将JSON数据传递给spring控制器?

I followed this tutorial and 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 状态:parsererror er:SyntaxError:意外发出

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;
}

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中,您还可以将数据作为data:'name='+ name+'&lastname='+ lastname,传递data:'name='+ name+'&lastname='+ lastname,在控制器端,您可以使用@RequestParam批注来获取从ajax调用传递的值。 Ajax code looks as follows: 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:) 干杯:)

  1. For sending the input data to controller, you don't have to necessarily use json as a format. 要将输入数据发送到控制器,您不必一定使用json作为格式。 You can simply pass them as request param and extract it on controller using @RequestParam annotation. 您可以简单地将它们作为请求参数传递,并使用@RequestParam批注将其提取到控制器上。 If you want to post json data you can use JSON.stringify(json). 如果要发布json数据,则可以使用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. 如果要将对象绑定到模型对象,请尝试在控制器上使用@Modelattribute并将数据传递到ajax帖子中。 There are plenty of examples for this. 有很多例子。
  2. Use @RequestParam or @RequestBody to get your data on your controller based on what approach you choose based on point 1. 根据基于第1点选择的方法,使用@RequestParam或@RequestBody在控制器上获取数据。
  3. 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. 使用@ResponseBody发送回数据,如果发送回json数据,则使用Json.parseJson转换为js对象,或者如果发送Map,则可以在ajax处理程序中获取JS对象。 You can use Dot notation to populate the data. 您可以使用点符号来填充数据。

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 Jackson lib. 如果要表示用户对象,则必须定义您的用户对象,并使用Jackson lib指定所需的字段。 It is a little tricky, but once you got it, you can pass any object you want. 这有点棘手,但是一旦获得,就可以传递任何想要的对象。

And then you can just pass your data in AJAX as defined in your controller. 然后,您可以按照控制器中定义的方式将数据传递到AJAX中。 So in this case would be: 因此,在这种情况下将是:

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 干杯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM