私は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);
});
AJAXリクエストですのでリクエストに時間がかかる場合があります。おそらく 'console.log(currentQuote)'を試す前に数秒待つかもしれません。 – SaschaP
この場合、クォートはJSプロパティには関係ありません。実際には 'Accept 'を使って有効にしてください。 – gyre
'$ .ajax'は非同期です。あなたはコードではありません。それは物語です。 – Nonemoticoner