使用ajax将参数传递给Controller

时间:2018-03-23 04:07:36

标签: java html mysql ajax spring-boot-maven-plugin

使用Spring启动,MySQL,JPA和RESTFUL CRUD API。

我要做的是将参数传递给Controller,以便参数进入表格。但是null值进入表中我无法确定哪个部分是问题。只有我能确定控制器没有收到适当的值。

在下面,我发布了Entity类(Status.java),Controller(GuideController.java)和html表单(guide.html)。

Status.java

@Entity
@Table(name="tbl_status")
public class Status {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)

private Integer id;

private String xml_to_json;


public String getXml_to_json() {
    return xml_to_json;
}

public void setXml_to_json(String xml_to_json) {
    this.xml_to_json = xml_to_json;
}

GuideController.java

    @Autowired
private StatusRepository statusRepository;

@GetMapping(path="/insert") // Map ONLY GET Requests
public @ResponseBody String addNewStatus (@RequestParam String xml_to_json
        , @RequestParam String json_to_xml) {
    // @ResponseBody means the returned String is the response, not a view name
    // @RequestParam means it is a parameter from the GET or POST request

    Status s = new Status();
    s.setXml_to_json(xml_to_json);
    //s.setJson_to_xml(json_to_xml);
    statusRepository.save(s);
    return "Saved";
}

@GetMapping(path="/all")
public @ResponseBody Iterable<Status> getAllUsers() {
    // This returns a JSON or XML with the users
    return statusRepository.findAll();
}

guide.html

var xml2json = function(_data){
$.ajax({   
    type: "POST",   
    url: url + "xml2json",   
    data: _data,
    contentType : "application/xml",
    cache: false,
    success : function(data) {   
        $("#output-xml-to-json").html(JSON.stringify(data,null,4));
        $.ajax({
            type:"POST",
            url: url + "insert",
            data: {xml_to_json:"success"},
            contentType: "text"
        })
    },
    error : function(){
        $("#output-xml-to-json").html("xml2json error");
        $.ajax({
            type:"POST",
            url: url + "insert",
            data: {xml_to_json:"error"},
            contentType: "text"
        })
    }
});

}

1 个答案:

答案 0 :(得分:0)

请求映射是GET:

@GetMapping(path="/insert") // Map ONLY GET Requests
public @ResponseBody String addNewStatus (@RequestParam String xml_to_json
    , @RequestParam String json_to_xml) {...}

AJAX请求是带有json数据的POST。应该获取AJAX请求,并且必须在查询字符串中传递xml_to_json