有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何将模型解析为ajax post调用

我试图用model.addAttribute("myModel",mymodelvariable);解析我用spring加载的一个模型到一个ajax调用(该模型正在表单中使用)
有没有办法调用我的Spring控制器并立即将该模型和数据发送回我的控制器?如果没有,如何使用ajax将表单的数据作为对象解析到我的控制器

以下是我使用@Html尝试的内容:

$('#sampleForm').submit(

    function(event) {
        var data = @Html.Raw(Json.Encode(Model));
        $.ajax({
            url: 'http://localhost:8080/hellohello',
            type : "POST",
            data : data,
            beforeSend: function (xhr) {
                xhr.setRequestHeader(header, token);
            },
            success : function(response) {
               $('#reloading').html(response);
            },
            error : function(err) {
                alert("not working")
                console.log("not working. ERROR: "+JSON.stringify(err));
            }
        });
        return false;
    });

控制器:

 @CrossOrigin(origins = "http://localhost:8080")
 @ResponseBody
 @RequestMapping(value = "/hellohello",method = RequestMethod.POST)
 public ModelAndView step1(@ModelAttribute Mymodelvariable mymodelvariable){

      //do stuff and return model
    }

共 (1) 个答案

  1. # 1 楼答案

    试试这个也许对你有帮助

    $('#sampleForm').submit(
    
    function(event) {
    
        var data={
            "name":$('#name').val(),
            "age":$('#age').val(),
            "xyz":$('#xyz'+str).val(),
            "xyz":$('#xyz'+str).val(),
            "xyz":$('#xyz'+str).val(),
            "xyz":$('#xyz'+str).val(),
            "xyz":$('#xyz'+str).val(),
    
           }
      $.ajax({
            url : "././hellohello",
            type : "POST",
            contentType : 'application/json; charset=utf-8',
            data: JSON.stringify(data),
            beforeSend: function (xhr) {
                xhr.setRequestHeader(header, token);
            },
            success : function(response) {
               $('#reloading').html(response);
            },
            error : function(err) {
                alert("not working")
                console.log("not working. ERROR: "+JSON.stringify(err));
            }
        });
        return false;
    });
    

    控制器类:

      @CrossOrigin(origins = "http://localhost:8080")
      @RequestMapping(value = "/hellohello",method = RequestMethod.POST)
       @ResponseBody
        public ModelAndView step1(@RequestBody Modelclass mymodelvariable)throws 
          Exception{
    
      //do stuff and return model
    }