在Rest API上查找搜索值并将其用于请求

时间:2019-03-05 09:15:33

标签: json ajax api get request

我想在rest API上搜索一个值,然后用返回的值发出另一个请求。

简单的搜索字段:

<div class="container">
  <h1>Wikipedia Search</h1>
  <input id="searchTerm" name="search" placeholder="Search..">
  <button id='search' type="button" class ="btn btn-primary">Submit</button>
</div>

Json看起来像这样:

{
    "status": "success",
    "games": [
        {
            "id": "1",
            "name": "counter"
        },
        {
            "id": "2",
            "name": "dota"
        },
        {
            "id": "3",
            "name": "aoe2"
        },
        {
            "id": "4",
            "name": "civ5"
        }]
}

我的目标是,当有人搜索“ counter”以将id 1作为变量返回时,我可以将其用于另一个休息的api get请求。

我正在尝试的JS代码:

$("#search").on("click", function() {
        var searchTerm = $("#searchTerm").val();
        var url = "https://www.website.com/api.php?action=games"; 
        $.ajax({
            url: url,
            type: 'GET',
            contentType: "application/json; charset=utf-8",
            async: false,
            dataType: "json",
          // plop data
            success: function(games, status, errors) {

                $("#output").html();
                for(var x in games){
            if(games[x].id && games[x].id.split(",").indexOf(id.toString())!=-1) return games[x].name;
            }
            return "Not Found";
            }});
          console.log(searchTerm)

    });

使用返回的ID值,我要发出一个get请求,如下所示: 例如var Id = *搜索返回的ID

var request = new XMLHttpRequest();
request.open('GET', 'https://website.com/api/player.php?aid='Id'', true);
request.onload = function () {


  var data = JSON.parse(this.response);
request.onreadystatechange = function() {
  if (this.readyState === 4) {
    if (this.status >= 200 && this.status < 400) {
      // Success!
      var data = JSON.parse(this.responseText);
    } else {
      // Error :(
    }
  }
};

0 个答案:

没有答案