【问题标题】:Autocomplete field with JSON data from external url (Steam API)带有来自外部 URL 的 JSON 数据的自动完成字段(Steam API)
【发布时间】:2020-04-03 15:00:54
【问题描述】:

我正在处理一个使用此链接(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


    【解决方案1】:

    在成功块中,您正在分配标签和 ID。在您指定名称的标签中,并在 id 中指定 appid。我们可以修改它以像这样格式化标签:

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

    【讨论】:

      【解决方案2】:

      第 31 行的 Javascript 中存在语法错误(基本上你有一个额外的右括号和分号)。

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

      【讨论】:

      • 感谢您帮助我修复语法错误。但是代码仍然无法正常工作。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-16
      • 2018-02-16
      • 2021-01-19
      • 1970-01-01
      • 2013-06-25
      • 1970-01-01
      相关资源
      最近更新 更多