我需要向 API 发出 AJAX 请求获取刽子手游戏的词。在读取单词长度并用占位符显示它方面也很挣扎。我引用了这个链接enter link description here ,但我仍然卡住了。
//function to get the word from the API using AJAX
jQuery.extend({
getValues: function(url) {
var result = null;
$.ajax({
url: url,
type: 'get',
dataType: 'xml',
async: false,
success: function(data) {
result = data;
}
});
return result;
}
});
//accessing global variable (word)
var results = $.getValues("https://hangman-api.lively.software");
for (var i < 0; i < word.length; i++) {
results[i] = "_";
}
最佳答案
希望我的代码片段可以在某些方面对您有所帮助。祝你今天过得愉快!
$(function(){
$.ajax({
url: "https://hangman-api.lively.software/",
type: 'get',
success: function(data) {
//how to access word
console.log(data.word)
//how to create placeholders
placeHolder = " _ ";
placeHolders = placeHolder.repeat(data.word.length)
//how to print place holder
$(".placeHolder").text(placeHolders)
}
});
})
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
Placeholders : <span class="placeHolder"></span>
</body>
</html>
关于javascript - 如何发出 AJAX 请求来获取单词并全局存储变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58419704/