2017-03-01 60 views
0

我想將JSON對象發佈到使用JQ的Ajax在Java中創建的REST,但是,我收到「不受支持的媒體類型」錯誤。使用JQ發佈JSON對象到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,因爲服務器應用程序沒有Jackson。現在我可以使用老式的方式工作,但我仍然無法修復JQ變體。這裏是老式的阿賈克斯代碼:

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; 

回答

0

我終於弄清楚了這個問題。

顯然,服務器應用程序需要有傑克遜(因此我現在使用不同的網址 - 這是一個不同的應用程序,有傑克遜)和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); 
});