LoginSignup
218

More than 5 years have passed since last update.

jQueryのajax()を利用すると返り値をとりたいときのやり方

Posted at

問題

jQueryのajaxで返り値がとれない

以下のtest()の結果はundefinedに

function test(){
    $.ajax({
        type: 'GET',
        url: 'http://kitagawa.keiko'
        dataType: 'text',
        success: function(response){
            return response;
        },
        error: function(response){
            return response;
        });
}

var result = test(); // undefined

原因

ajax()はデフォルトで非同期通信をするため。非同期通信はレスポンスが返る前に次の処理にいく。

解決策

基本的には2番めの方がおすすめ。

その1.同期通信にする

async: falseとすると、同期通信になる。 ただし同期通信の場合は時間がかかる処理をすると、その間UIがロックされてしまう。なのであまりやらない方がいい。

function test(){
    var result = $.ajax({
        type: 'GET',
        url: 'http://kitagawa.keiko',
        async: false
    }).responseText;
    return result;
}

var result = test() //ちゃんと返り値が入ってる;

その2..done, .fail()をつかう

これだと、非同期通信のまま返り値を得ることができる。こっちの方がおすすめ。

function test(){
    return $.ajax({
        type: 'GET',
        url: 'http://kitagawa.keiko'
    })
}

test().done(function(result) {
    なんか処理
}).fail(function(result) {
    なんか処理
});

(参考)http://tkmr.hatenablog.com/entry/2014/08/08/084755

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
218