简体   繁体   中英

How to make an AJAX request to get a word and store the variable globally

I need to make an AJAX request to API to get the word for a hangman game. Also struggling, on reading the word length and displaying it with placeholders. I referenced this link enter link description here , but am still stuck.

//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] = "_";
  }

Hopefully my snippet can help you in some ways. have a nice day!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM