【问题标题】:Passing Json object from java script to java将 Json 对象从 java 脚本传递到 java
【发布时间】:2017-06-28 18:57:42
【问题描述】:

我是 springs 和 ajax 的新手 我的java脚本中有一个动态创建的json对象 我需要使用 ajax 或普通 submit() 从 java 脚本发送这个 json 对象

如果它是一个字符串,我们有隐藏的输入。

据我所知,如果我没记错的话 一个我们无法隐藏的 JSON 对象

而且我必须使用 java 代码接收。 这是我的脚本

$(document).ready(function(){
    // click on button submit
    $("#save_btn").on('click', function(){
        alert();
        // send ajax
        $.ajax({
            url: 'project_reg_save', // url where to submit the request
            type : "POST", // type of action POST || GET
            dataType : 'json', // data type
            data : $("#reg_form").serialize(), // post data || get data

            success : function(result) {
                // you can see the result from the console
                // tab of the developer tools
                console.log(result);
            },
            error: function(xhr, resp, text) {
                console.log(xhr, resp, text);
            }
        })
    });
});

这是我的java代码

@Controller
public class Save {
    @RequestMapping("/project_reg_save")

    public ModelAndView mymethod(@RequestParam JSONObject obj)//which is not possible  {

        System.out.println(obj);

        return new ModelAndView("Product_reg", "msg", "product Registration");
    }
}

【问题讨论】:

  • 也许尝试将其作为字符串传递,然后使用 Java 对其进行序列化?
  • 不是请求参数,是请求体。尝试将注解改为@RequestBody,并在@RequestMapping中添加consumes = {MediaType.APPLICATION_JSON_VALUE}

标签: javascript java json ajax spring-mvc


【解决方案1】:

一个解决方案是

  1. 将您的 dataType : 'json' 更改为 dataType : 'text'
  2. @RequestParam JSONObject obj 到 @RequestParam String obj
  3. JsonObject JsonObj= new JsonParser().parse(obj).getAsJsonObject();

因此你得到 json 对象

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-28
    • 2012-03-29
    • 1970-01-01
    • 1970-01-01
    • 2011-03-23
    • 2018-02-27
    • 2023-03-25
    • 1970-01-01
    相关资源
    最近更新 更多