LoginSignup
6
7

More than 5 years have passed since last update.

JS(javascript)でajaxの通信部分を同期的にして共通化する

Last updated at Posted at 2017-11-21

よく新しいプロジェクトに行くと書き方忘れてググるのに時間がかかるのでメモ。

サンプルとして作るものは2ファイル4ファンクション。

  • test.js(ajaxの通信部分を呼び出す処理と戻ってきてからの処理を書くファイル)

    • test
    • testSuccess
    • testError
  • common.js(ajaxの通信部分を書く共通ファイル)

    • connect
test.js
// html側で両方呼び出してれば書く必要なし
document.write("<script type='text/javascript' src='js/common.js'></script>");

// 参照先:common.js
function test () {

    var actionPath = '/xxx/xxxx';

    var param =  {
        'code' : 'xxxxxxx',
    };

    // result = connect(HTTPメソッド, パス, パラメータ, 正常時ファンクション, 異常時ファンクション);
    result = connect('POST', 'actionPath', param, testSuccess, testError);
}

// testで同期処理にするための正常時コールバック関数
function testSuccess(data){
    // 正常処理の実装
}

// testで同期処理にするための異常時コールバック関数
function testError(data){
    // 異常処理の実装
}
common.js
// ajax通信をする
function connect(type,actionPath, param, successCallBack, errorCallBack) {

    //* ajax
    $.ajax({
        type: type,
        dataType: 'json',
        url: 'http://'+location.host+actionPath,
        data: param
    }).done(function (data, textStatus, xhr) {
        //* success
        if (data.status) {
            return successCallBack(data);
        } else {
            return errorCallBack(data);
        }

    }).fail(function(xhr, stat, e){
        //*  error 
        //console.log(xhr);
        return 'fail error';

    }).always(function(data){
        // --
    });

}

正直ajaxのソースでxhrとか理解してないところは多々あるのですが^^;
まぁ、よくこんな感じでajaxで値を引っ張ってきてそれを使いたいって時は
これを使って、同期的にして非同期で値が引っ張れてないのに処理が進むというのを回避してます。

6
7
1

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
6
7