2017-03-01 26 views
0

JQのAjaxを使用してJavaで作成されたRESTにJSONオブジェクトを投稿しようとしていますが、「サポートされていないメディアタイプ」エラーが発生しています。ここでJQを使用してRESTにJSONオブジェクトを投稿する

は、コントローラのメソッドである:ここで

@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です:

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); 
}); 

EDIT:ここ

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でこれでも動作しないでしょうが判明しますサーバーアプリケーションにジャクソンがいないため、私は旧式のAjaxを使用しました。私はlibを使用しているので、今は古き良き方法で作業することができますが、まだ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; 

答えて

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); 
}); 
関連する問題