简体   繁体   English

Ajax JQuery 到 Spring @RequestBody? 我如何传递数据?

[英]Ajax JQuery to Spring @RequestBody? How do I pass data?

Ajax JQuery to Spring @RequestBody? Ajax JQuery 到 Spring @RequestBody? How do I pass data?我如何传递数据? I being doing spring for sometime now with passing form fields but I am working on a new system and we would like to use Ajax and RESTful to pass data.我现在正在通过传递表单字段来做春天,但我正在开发一个新系统,我们想使用 Ajax 和 RESTful 来传递数据。 My controller looks like the sample one below but can someone please me with the ajax call to post it??我的控制器看起来像下面的示例,但有人可以通过 ajax 调用来取悦我吗? how do I post to the Spring controller and put the data in the body我如何发布到 Spring 控制器并将数据放在正文中

@RequestMapping(method=RequestMethod.PUT, value="/employee/{id}")
public ModelAndView updateEmployee(@RequestBody String body) {
        Source source = new StreamSource(new StringReader(body));
        Employee e = (Employee) jaxb2Mashaller.unmarshal(source);
        employeeDS.update(e);
        return new ModelAndView(XML_VIEW_NAME, "object", e);
    }

When using REST, it's important to understand the distinction between the different HTTP methods.使用 REST 时,了解不同 HTTP 方法之间的区别很重要。 PUT generally means that you're going to create a new collection or replace an existing one. PUT 通常意味着您将创建一个新集合或替换现有集合。 POST generally means that you're adding a record to a collection. POST 通常意味着您将记录添加到集合中。 The main difference between the two is that PUT is idempotent, which means that repeating the same operation repeatedly doesn't change the state of the server.两者的主要区别在于 PUT 是幂等的,这意味着重复相同的操作不会改变服务器的状态。

In your code below, you're method is called "updateEmployee", which implies you're replacing a collection with a new one.在下面的代码中,您的方法称为“updateEmployee”,这意味着您正在用一个新集合替换一个集合。 Thus, PUT is the most appropriate HTTP Method to use in this scenario.因此,PUT 是在这种情况下使用的最合适的 HTTP 方法。 However, you have a bug in your code.但是,您的代码中有一个错误。 You didn't define the "id" in the parameter list:您没有在参数列表中定义“id”:

// Added String id as a PathVariable
@RequestMapping(method=RequestMethod.PUT, value="/employee/{id}")
public ModelAndView updateEmployee(@RequestBody String body, @PathVariable String id) {   

        // You really don't need to do this. The Spring Framework can deserialize
          // objects for you. However, one issue at a time ;)
           // also, changed e to "employee" so the variable has a better name.
        Source source = new StreamSource(new StringReader(body));
        Employee employee = (Employee) jaxb2Mashaller.unmarshal(source);

        employeeDS.update(employee);
        return new ModelAndView(XML_VIEW_NAME, "object", employee);
}

To make the request to the server, use jQuery AJAX:要向服务器发出请求,请使用 jQuery AJAX:

$.ajax({
  url: "/employee/2?t="+new Date().getTime(),
  contentType: 'application/x-www-form-urlencoded',
  type: "PUT",
  data: dataString,
  context: document.body,
  success: function(e){
          alert(e);                    
  },
      error: function(jqXHR, textStatus, errorThrown) {
          alert(" + textStatus + " : " + errorThrown);
      } 
});

dataString is a string representation of your data. dataString 是数据的字符串表示形式。 You can either serialize the form, use JSON, or send a url-encoded form.您可以序列化表单、使用 JSON 或发送 url 编码的表单。 Without seeing more code and more error messages in your question, it's unclear how you're representing your data when attempting to send it to the server.如果在您的问题中没有看到更多代码和更多错误消息,则不清楚您在尝试将数据发送到服务器时如何表示数据。 If you start here and fix the above errors in your Java code, this should get you past this specific error.如果您从这里开始并修复 Java 代码中的上述错误,这应该可以帮助您克服这个特定错误。

Another way to submit data to your REST method, just for testing, is to use a standard form, but use method="PUT", since that's what you're using in Spring:另一种将数据提交到 REST 方法(仅用于测试)的方法是使用标准表单,但使用 method="PUT",因为这是您在 Spring 中使用的:

<form name="test" action="/employee/2" method="PUT">
    <input type="text" name="firstname" />
    <input type="text" name="lastname" />
    <input type="submit" name="submit" value="submit" />
</form>

This will use application/x-www-form-urlencoded.这将使用 application/x-www-form-urlencoded。 If you're unable to deserialize that, then try using JSON instead.如果您无法反序列化,请尝试改用 JSON。 Good luck!祝你好运!

Hope gives you a start!希望能给你一个开始!


$.ajax({
    contentType : "application/json",
    dataType : 'json',
    type : "PUT",
    url : targetUrl,
    data : $(this).serializeObject(), //json serialization (like array.serializeArray() etc)
    async : false,
    success : function(data) {
       // response
    },
    error : function(request, status, error) {
       // any errors
    }
});

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

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