使用JQ

时间:2017-03-01 10:29:59

标签: ajax

我正在尝试使用JQ的Ajax将JSON对象发布到使用Java创建的REST中,但是,我得到了"不支持的媒体类型"错误。

这是控制器方法:

@ResponseBody
@RequestMapping(value = "postrest", method = RequestMethod.POST, consumes = "application/json")
public String postRest(@RequestBody Person person) throws InterruptedException{
    Thread.sleep(5000);
    return "Congrats on successfully posting, " + person.getName() + "!";
}

这是pojo:

package domain;

public class Person {

    private String name;

    public Person(){}

    public Person(String name){
        this.name = name;
    }


    public String getName() {
        return name;
    }


    public void setName(String name) {
        this.name = name;
    }

}

这是JavaScript:

var person = {};
person.name = "milan";

$.ajax({
url: "http://localhost:8084/app/postrest",
type: "post",
data: person,
contentType: "application/json; charset=utf-8",
dataType: "text",
  context: document.body
}).done(function(response) {
  console.log(response);
});
编辑:事实证明,即使我使用了老式的Ajax,这也不会起作用,因为服务器应用程序没有杰克逊。我现在可以使用老式的方式工作,但是,我仍然无法修复JQ变体。这是老式的Ajax代码:

var person = {};
person.name = "milan";

var xhr = new XMLHttpRequest();
xhr.open("post", "http://localhost:8084/springsecurityalternative/postrest", false); //notice that the URL is different here, this is because I'm running using a different app that has Jackson
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(JSON.stringify(person));

xhr.responseText;

1 个答案:

答案 0 :(得分:0)

我终于找到了问题。

显然,服务器应用程序需要有杰克逊(因此我现在使用不同的URL - 它是一个不同的应用程序,有杰克逊)和JQ代码应该看起来像这样(我忘记了JSON.stringify()正在发送的数据):

var person = {};
person.name = "milan";

$.ajax({
url: "http://localhost:8084/springsecurityalternative/postrest",
type: "post",
data: JSON.stringify(person),
contentType: "application/json", //data type being sent to the server
//dataType: "json", //data type expected from the server
   //context: document.body //by default set to document
}).done(function(response) {
  console.log(response);
});