2016-12-08 4 views
-3

私はgetQuotes()、およびにconsole.log(と呼ばれるこの機能を持っている)それの終わりにcurrentQuoteの正しい値を示しています。その後、私はのgetFunction(呼び出したとき)(下記のコードのように)、私の変数currentQuoteにconsole.logを示し、それはまだ、それを正しい値を受信して​​いない:VAR - Javascriptを

function getQuote() { 
     $.ajax({ 
      headers: { 
       "X-Mashape-Key": "xxx", 
       Accept: "application/json", 
       "Content-Type": "application/x-www-form-urlencoded" 
      }, 
      url: 'https://andruxnet-random-famous-quotes.p.mashape.com/?cat=movies', 
      success: function(response) { 
        var r = JSON.parse(response);  
        currentQuote = r.quote; 
        currentAuthor = r.author; 
        console.log(currentQuote);    
      } 
     }); 
}; 

ポイントがあります宣言された空文字列。私は間違って何をしていますか?

$(document).ready(function() { 
    var currentQuote=''; 
    var currentAuthor='';    
    getQuote(); 
    console.log(currentQuote);   
}); 
+1

AJAXリクエストですのでリクエストに時間がかかる場合があります。おそらく 'console.log(currentQuote)'を試す前に数秒待つかもしれません。 – SaschaP

+2

この場合、クォートはJSプロパティには関係ありません。実際には 'Accept 'を使って有効にしてください。 – gyre

+1

'$ .ajax'は非同期です。あなたはコードではありません。それは物語です。 – Nonemoticoner

答えて

0

2つの別の問題があります。

まず、ドキュメント対応のコールバックから最後のconsole.logを削除し、AJAXリクエストの成功コールバックがあなたのためにロギングを行うことを許可します。グローバルなもののセットと、ドキュメント、準備コールバックにローカルにスコープされるセット:

第二に、あなたはcurrentQuotecurrentAuthor変数の2セットを持っています。あなた明示的衝突を防ぐために、そのように、グローバルプロパティとしてそれぞれの変数を定義する必要があります。

$(document).ready(function() { 
    window.currentQuote = '' 
    window.currentAuthor = ''    
    getQuote()   
}); 

function getQuote(cb) { 
    $.ajax({ 
     headers: { 
      "X-Mashape-Key": "xxx", 
      Accept: "application/json", 
      "Content-Type": "application/x-www-form-urlencoded" 
     }, 
     url: 'https://andruxnet-random-famous-quotes.p.mashape.com/?cat=movies', 
     success: function (response) { 
       var r = JSON.parse(response)  
       window.currentQuote = r.quote 
       window.currentAuthor = r.author 
       console.log(currentQuote)  
     } 
    }) 
} 

あなただけの引用符と作者を記録以上のことをやりたい場合は、あなたを作るためにいくつかの方法があります人生はもう少し簡単です:コールバックと約束。

コールバックは別の(非同期)関数にパラメータとして渡され、非同期処理が完了したとき(あなたの引用と著者のような)いくつかの「戻る」値で呼び出される関数です。ここでは、コールバック関数としてresolveを使用しています。

$(document).ready(function() {    
    getQuote(function (quote, author) { 
     // callback -- do stuff with `quote` and `author` 
     console.log(quote, author) 
    }) 
}) 

function getQuote(resolve) { 
    $.ajax({ 
     headers: { 
      "X-Mashape-Key": "xxx", 
      Accept: "application/json", 
      "Content-Type": "application/x-www-form-urlencoded" 
     }, 
     url: 'https://andruxnet-random-famous-quotes.p.mashape.com/?cat=movies', 
     success: function (response) { 
       var result = JSON.parse(response)  
       resolve(r.quote, r.author) 
     } 
    }) 
} 

約束は、非同期コードを処理するための、より近代的な方法ですが、彼らはまた、あまり広く(これはポリフィルを改善することができる)デフォルトでサポートされています。約束はこの回答の範囲外ですが、もっと情報が必要な場合は、the Promise page on the Mozilla Development Networkをチェックすることをお勧めします。

+0

私は、成功して実行される引数としてコールバックを渡すことをお勧めします。 – Nonemoticoner

+0

もちろん、それは可能です。プロミスを使用することもできます。それが助けになるなら、コールバックについての少しの宣伝を追加します。 – gyre

1

getQuote()は、Ajax呼び出しを使用するため、getQuote()を呼び出すと、操作は非同期に進みます。つまり、getQuote()が返っても、結果はまだ利用できません。あなたはgetQuote()に引数としてコールバック機能を提供し、success関数からその関数を呼び出すことによってこの問題を解決することができます

function getQuote(callback) { 
    $.ajax({ 
     headers: { 
      "X-Mashape-Key": "xxx", 
      "Accept": "application/json", 
      "Content-Type": "application/x-www-form-urlencoded" 
     }, 
     url: 'https://andruxnet-random-famous-quotes.p.mashape.com/?cat=movies', 
     success: function(response) { 
       var r = JSON.parse(response);  
       callback(r.quote, r.author); // Report success to the caller 
     } 
    }); 
}; 

その後:

$(document).ready(function() { 
    getQuote(function(currentQuote, currentAuthor) { 
     console.log(currentQuote); 
    }); 
}); 

これもグローバルcurrentQuoteの必要性を排除し、 currentAuthor変数。 (値が他の場所で必要とされている場合は常に、コールバックのものを割り当てることができますが。)

代替

あなたはgetQuoteからPromiseを返すと約束のresolveメソッドを呼び出すためにAjax呼び出しを変更することができます。これは、これが重複しているスレッドの受け入れられた答えに記述されています。

あなたはjQueryのを使用しているため、コールバック関数を渡すことに別の代替は便利done(result)プロパティを持つajaxオブジェクト自体を、返すことです。その後、

function getQuote() { 
    return $ajax({ 
     headers: { 
      "X-Mashape-Key": "xxx", 
      "Accept": "application/json", 
      "Content-Type": "application/x-www-form-urlencoded" 
     }, 
     url: 'https://andruxnet-random-famous-quotes.p.mashape.com/?cat=movies', 
    }); 
} 

と使用:

$(document).ready(function() { 
    getQuote().done(function(result) { 
     if (result) { 
      var r = JSON.parse(response); 
      console.log(r.quote); 
     } 
    }); 
}}; 

これは、重複スレッドでも説明されています。詳細については、the docs for $ajax()を参照してください。