如何发出AJAX请求以获取单词并将其全局存储

时间:2019-10-16 18:36:12

标签: javascript

我需要向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] = "_";
  }

1 个答案:

答案 0 :(得分:1)

希望我的代码段可以在某些方面为您提供帮助。祝你今天愉快!

$(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>