Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.

問題

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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした