我有一個php文件,它的echo是一個json編碼的詞。我有一個JavaScript函數來檢索這個詞。我想調用這個函數,檢查返回的單詞是否已經在一個數組中,如果是,我想調用另一個單詞。我基本上想重複這個過程,直到我得到一個不在我的數組中的單詞。我正在努力,所以我需要一些建議如何做到這一點。我只想在客戶端做到這一點。目前,當我調用getWord()時,它返回undefined,但函數本身起作用,所以我懷疑當時還沒有檢索到該單詞。反覆調用一個打php文件的函數
<?php
$sql = "SELECT * FROM words ORDER BY RAND() LIMIT 1";
$result = $db->query($sql);
$row = $result->fetch_assoc();
$word = $row['word'];
echo json_encode($word);
?>
function getWord(){
var word;
$(document).ready(function(){
$.getJSON("getWord.php",function(data){
word = data;
alert("1st alert: " + word);
});
});
return word;
}
$(document).ready(function() {
$("#newRound").on("click",function(){
currentWord = getWord();
alert("SEcond alert: " + currentWord);
//check here if data is already in wordsSoFar arary and if it is, get another word from getword.php
document.getElementById("input1").style.visibility = 'visible';
//currentWord = data; //set the current work
lives = 6; //reset lives
tracker = 0;
incorrectLettersGuessed = "";
allGuessedLetters = "";
updateLetters();
document.getElementById('hangman').innerHTML = '<center><img src="stage1.png"></center>';
createTable(currentWord);
output.innerHTML = '<center>'+messages.validLetter + '</center>';
alert(currentWord);
});
});
getWord.php的來源在哪裏?順便說一句,'$ .getJson()'是一個[異步](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests)方法。你的getWord()函數總是會返回一個空值。 –
它只是一個單詞數據庫。只有在getWord()被競爭後調用方法之後纔有辦法執行代碼嗎? –
它提醒這個詞嗎?如果是這樣,那麼請查看我在第一條評論中發佈的關於_asynchronous_的鏈接。 –