我有一个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_的链接。 –