LoginSignup
2
4

More than 5 years have passed since last update.

【jQuery】ajax-config.jsなるものを作ってみた。(Spring Security利用時にも使える)

Last updated at Posted at 2018-02-25

このJavaScriptを好きにカスタマイズして、ajaxメソッドのトップで読み込めば設定が全体に生きる。

thymeleaf

sample.html
    <!--/* CSRFトークン取得用metaタグ */-->
    <meta name="_csrf" th:content="${_csrf.token}" />
    <meta name="_csrf_header" th:content="${_csrf.headerName}" />

ajax-config.js

ajax-config.js

///////////////////////////////////////////////////////////////////////////////////////////////
// Ajax通信の設定
///////////////////////////////////////////////////////////////////////////////////////////////
$(function () {
    /**
     * layout.htmlから取得したコンテキストパス.
     * 例)/elabel/edit にアクセスしたい場合は「contextPath + 'elabel/edit'」がURLとして利用できる.
     */
    contextPath = $('#contextPath').val();
});

/**設定を変更したい場合は個別JSファイル内のAjaxメソッドにオプションを記述して上書き */
(function () {
    $.ajaxSetup({
        cache: false, /** 一度使用したAjax通信のレスポンスをキャッシュさせない. */
        timeout: 15000, /** タイムアウト設定(暫定) */
        beforeSend: function (xhr, settings) { /** 通信開始直前の処理 */
            setCsrfTokenToAjaxHeader();
            // ここにクルクルGIFが動き出す処理とか入れるといい感じ
        },
        success: function (data, status, xhr) { /**通信成功時の処理 */
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {/**通信失敗時の処理 */
            console.log("ajax通信に失敗しました");
            console.log("XMLHttpRequest : " + XMLHttpRequest.status);
            console.log("textStatus     : " + textStatus);
            console.log("errorThrown    : " + errorThrown.message);
        },
        complete: function (xhr, status) { /**通信完了時の処理(エラーか否かに関わらず) */
            // ここにクルクルGIFを止める処理とか入れるといい感じ
        },
    });
})();

/**
 * Spring SecurityのCSRF対策によるトークンをajax通信のヘッダに埋め込める関数.
 * 利用するAjax通信の直前に呼び出す形で利用してください.
 */

function setCsrfTokenToAjaxHeader() {
    var token = $("meta[name='_csrf']").attr("content");
    var header = $("meta[name='_csrf_header']").attr("content");
    $(document).ajaxSend(function (e, xhr, options) {
        xhr.setRequestHeader(header, token);
    });
}
2
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4