JQuery将JSON发送到Spring MVC控制器

car*_*rlo 4 ajax model-view-controller jquery spring json

我无法将带有JQuery Ajax的JSON对象发送到Spring MVC控制器.这是我的控制器方法的定义:

@Controller
@RequestMapping(value = "InboxViewTemplate")
public class InboxViewController {

@ResponseBody
    @RequestMapping(value = "updateInboxView")
    public String updateInboxView(HttpServletRequest request, InboxView inboxView) {
...
}
Run Code Online (Sandbox Code Playgroud)

然后我试图调用这个请求:

$.ajax({
            dataType: 'json',
            contentType: "application/json",
            url: ctx + "/InboxViewTemplate/updateInboxView",
            data: ({inboxView : {createUser:"dave"}}),
            success: function(data) {
                $("#updateInboxView").html(data);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert(jqXHR + " : " + textStatus + " : " + errorThrown);
            }
          });
      }
Run Code Online (Sandbox Code Playgroud)

但是没有传递JSON对象.有人能帮我吗?提前致谢.

sou*_*eck 8

首先,您的控制器不知道在哪里寻找InboxView.这是一个请求参数吗?路径参数?请求机构?

其次,您可能希望将json请求类型更改为POST或PUT,因为您正在更新数据而不仅仅是检索它.

所以像这样:

@Controller
@RequestMapping(value = "InboxViewTemplate")
public class InboxViewController {

@ResponseBody
    @RequestMapping(value = "updateInboxView", method = RequestMethod.POST)
    public String updateInboxView(HttpServletRequest request, @RequestBody InboxView inboxView) {
    ...
} 
Run Code Online (Sandbox Code Playgroud)

$.ajax({
            dataType: 'json',
            contentType: "application/json",
            url: ctx + "/InboxViewTemplate/updateInboxView",
            type: 'POST',
            data:  JSON.stringify({inboxView : {createUser:"dave"}}), //if no JSON is available use the one from https://github.com/douglascrockford/JSON-js
            success: function(data) {
                $("#updateInboxView").html(data);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert(jqXHR + " : " + textStatus + " : " + errorThrown);
            }
          });
      }
Run Code Online (Sandbox Code Playgroud)

应该管用.

我假设您已正确配置了json消息转换器.

编辑 意思是:

<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
 <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
  <list>
    <ref bean="jacksonMessageConverter"/>
  </list>
</property>
</bean>
Run Code Online (Sandbox Code Playgroud)

或者类似于spring xml配置中其他消息转换器的东西.