使用 Ajax 将 json 发送到 Spring MVC [英] Send json with Ajax to Spring MVC

查看:33
本文介绍了使用 Ajax 将 json 发送到 Spring MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将带有 Ajax 的 json 发送到 Spring MVC 控制器,但我什么也得不到,我不知道我失败了什么

I want to send a json with Ajax to the Spring MVC controller but I can not get anything, I do not know what I'm failing

Javascript:

Javascript:

   var search = {
      "pName" : "bhanu",
      "lName" :"prasad"
   }

   var enviar=JSON.stringify(search);

    $.ajax({
      type: "POST",
      contentType : 'application/json; charset=utf-8',
      url: 'http://localhost:8080/HelloSpringMVC/j',
      data: enviar, // Note it is important
      success :function(result) {
       // do what ever you want with data
     }
  });

Spring MVC:

Spring MVC:

@RequestMapping(value ="/j", method = RequestMethod.POST)
     public void posted(@RequestBody Search search) {
         System.out.println("Post");
         System.out.println(search.toString());
     }

推荐答案

我觉得你把事情搞复杂了,事实上,如果你定义了一个Search 对象,你可以直接将数据传递给Controller方法,SpringMVC会为你形成一个搜索对象的实例,尝试如下:

I think you made things complicated,in fact,if you have a Search object defined,you can past the data directly to the Controller method,and SpringMVC will form an instance of the search object for you,try as below:

var search = {
      pName : "bhanu",
      lName :"prasad"
};

$.ajax({
  type: "POST",
  url: 'j',//do not put the full url,you need use an absolute url
  data: search,//put search js object directly here
  success :function(result) {
   // do what ever you want with data
 }

现在你可以得到如下搜索对象:

Now you can get the search object as below:

 @RequestMapping(value ="/j", method = RequestMethod.POST)
 public void posted(Search search) {
     System.out.println("Post");
     System.out.println(search.toString());
 }

这篇关于使用 Ajax 将 json 发送到 Spring MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆