简体   繁体   中英

Autocomplete field with JSON data from external url (Steam API)

I am working on an input field that is autocompleted with names from this link(steam API):

http://api.steampowered.com/ISteamApps/GetAppList/v0002/?format=json

or

http://api.steampowered.com/ISteamApps/GetAppList/v0001

I would also like the field to return the id of the game despite the name being insered into it.

So far after browsing the forums I put together this but it doesn't quite work:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Autocomplete - Default functionality</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
  $( function() {
    $("#tags").autocomplete({
        source: function (request, response) {
            $.ajax({
                url: "http://api.steampowered.com/ISteamApps/GetAppList/v0002/?format=json",
                data: { query: request.term },
                success: function (data) {
                    var transformed = $.map(data, function (el) {
                        return {
                            label: el.appid + " - " + el.name,
                            id: el.appid
                        };
                    });
                    response(transformed);
                },
                error: function () {
                    response([]);
                }
            });
          }
      });
  });
  </script>
</head>
<body>

<div class="ui-widget">
  <label for="tags">Tags: </label>
  <input id="tags">
</div>


</body>
</html>

For the autocomplete part I chose to use jQuery autocomplete function: https://jqueryui.com/autocomplete/ however I am open to other methods.

Edit: Fixed syntax error on line 31 but the code still isn't working.

JSFiddle: https://jsfiddle.net/vxej2L5g/

In the success block you are assigning a label and id. In the label you have assigned name, and in id the appid. We can modify this to format the label like this:

success: function (data) {
   var transformed = $.map(data, function (el) {
      return {
         label: el.appid + " - " + el.name,
         id: el.appid
      };
   });
   response(transformed);
},

There is a syntax error in your Javascript on line 31 (basically you have an extra closing parenthesis and semicolon).

The JSON response for the API you are calling wraps the list of apps.

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