0

Pulling out my hair. Countless hours trying to get ajax call to work...

Jquery:

function doAjaxPost(episode_id) {

    alert("cc");
    $.ajax({
        type: "POST",
        url: "http://localhost:8080/yay/episodes/remove",
        data: JSON.stringify({
            episode_id : episode_id
        }), 
        dataType: 'json',
        contentType: "application/json",
        success: function(){

            alert("o");
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            console.error(errorThrown);
        }
    });
}; 

Controller:

    @RequestMapping(value = "/episodes/remove", method = RequestMethod.POST)
    @ResponseStatus(value = HttpStatus.OK)
    public void removeEpisodeFromList(@RequestBody String episode_id) {

        System.out.println("Episode_id : " + episode_id);       
    }

And I call the function from:

<a href = "#" onclick = "doAjaxPost(${episode.episode_pk});"> MARK AS WATCHED </a>

It reaches the controller where the correct thing is printed out. But then FireBug just says "SyntaxError {}" and success function alert is never called.

4

1 に答える 1

1

渡されるデータにはおそらく影響しませんが、実際には data パラメーターに JSON.stringify アクションは必要ありません。http://api.jquery.com/jQuery.ajax/#example-0を参照してください

また、Spring MVC コントローラーから JSON を取得しようとしている場合は、@ResponseBody アノテーションを使用する必要があります。これにより、Spring はテンプレートをレンダリングしようとしなくなります。少し前に、Spring MVC アプリケーションから JSON を取得することについてのブログ記事を実際に書きました。

ここの「@ResponseBody アノテーションを使用して応答本文をマッピングする」というタイトルのセクションで、詳細を確認できます。

また、success() 関数は廃止されました。done() 関数を使用する必要があります。詳細については、上記の jquery の URL を参照してください。

お役に立てれば!

http://benashby.com/spring/response-body-annotation

于 2013-09-04T20:36:08.290 に答える