带有来自外部URL(Steam API)的JSON数据的自动完成字段

问题描述 投票:0回答:2

我正在使用此链接(Steam API)中的名称自动完成的输入字段:

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

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

我也希望该字段返回游戏的ID,尽管将名称插入其中。

到目前为止,在浏览了论坛之后,我将其放在一起,但效果不佳:

<!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>

对于自动完成部分,我选择使用jQuery自动完成功能:https://jqueryui.com/autocomplete/,但是我可以使用其他方法。

编辑:修复了第31行的语法错误,但是代码仍然无法正常工作。

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

javascript jquery steam steam-web-api
2个回答
0
投票

在成功块中,您将分配标签和ID。在标签中,您分配了名称,在id中指定了appid。我们可以修改它来格式化标签,如下所示:

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

0
投票

第31行的Javascript中存在语法错误(基本上,您有一个多余的右括号和分号)。

您正在调用的API的JSON响应将包装应用列表。

© www.soinside.com 2019 - 2024. All rights reserved.