将数据从搜索栏发送到网址

时间:2019-11-26 22:11:25

标签: javascript html api

我遇到麻烦了。所以我需要从api获取数据。我有一个搜索栏,用户需要输入搜索栏才能查找超级英雄api。

我该如何从搜索栏中获取数据,并将网址全部放在.click函数中。

var userInput;
var url;
var test;
//https://superheroapi.com/api/10215865526738981

$(document).ready(function () {
  // when the user types in the data and clicks the button
  $(btn1).click(function () {
    // this is where the search bar is
    userInput = document.getElementById('mySearch').innerHTML;
  });

  url = 'https://www.superheroapi.com/api.php/10215865526738981/search/batman' + userInput;

  // here is where the api link in say type in batman 
  // and is should pop up with info  about batman and

  $.getJSON(url, function (data) {
    var html = '';

    $.each(data.results, function (i, demo) {
      html += '<h2>' + demo.name + '</h2>';
      //html += "<h2>" + demo.biography.alter-egos + "</h2>";
      html += '<h2> Power Stats ' + demo.powerstats.combat + '</h2>';
      html += '<p> Connections ' + demo.connections.relatives + '</p>';
      html += '<p> appearance ' + demo.appearance.gender + '</p>';
      html += '<h2> Work ' + demo.work.base + '</h2>';
      html += ' Profile <img src ' + demo.image.url + '>';
    });

    $('#demo').html(html);
  });
}

<p>
  <input type="search" id="mySearch" name="mySearch">
  <button id="btn1">Search</button>
  <p id="demo"></p>
</p>

2 个答案:

答案 0 :(得分:1)

这是一种行之有效的东西,您可以用来与您的代码进行比较并从中做出一些事情。我使用了普通的javascript并留下了评论,说明发生了什么,以便您可以从中学到东西。

原始问题中几乎没有错误的假设。

  • 代码是在页面加载时执行的,没有等待用户输入
  • URL被严格编码为以batman +用户所写的内容开头

下面的代码并不完美,但是它与原始代码足够接近,应该易于理解。我还选择不使用jQuery,但如果需要,您应该可以使用它。只需用jQuery选择器替换getElementById并用XMLHttpRequest替换getJson

我希望这可以帮助您解决问题,并能够学习一些新的知识,以帮助您更好地理解javascript。编码愉快!

var button = document.getElementById('btn1');
// when user clicks on button, we want to call function start search
button.addEventListener('click', startSearch);

function startSearch(event) {
  // when we are starting the search, we want to pick up the value
  // input field from user
  var userInputValue = document.getElementById('mySearch').value;
  // this is base API url on which we can add what user wanted
  var urlBase = 'https://www.superheroapi.com/api.php/10215865526738981/search/'
  // if user did not provide name in input, we want to stop executing
  if (userInputValue === null || userInputValue === '') return;
  // if we are still in this function, append what user typed onto urlBase
  var searchUrl = urlBase + userInputValue;
  // call function which actually executes the remote call 
  performSearch(searchUrl);
}

function performSearch(searchUrl) {
  // this could be jQuery getJSON if you so prefer
  // here it is vanila JS solution of how to get data via AJAX call
  var requestData = new XMLHttpRequest();
  // because AJAX is always async, we need to wait until file is loaded
  // once it is loaded we want to call function handleResults
  requestData.addEventListener('load', handleResults);
  requestData.open('GET', searchUrl);
  requestData.send();
}

function handleResults() {
  // once we get response, because we used vanilla JS, we got response
  // available in this context as "this.response", however it is type string
  // we need to take that string and parse it into JSON
  var responseJSON = JSON.parse(this.response);
  // if there is error, we didn't find any character
  if (responseJSON.error) console.log('Character not found');
  else {
    var html = '';
    responseJSON.results.forEach(function (result)  {
      html += '<h2>' + result.name + '</h2>';
      // html += "<h2>" + demo.biography.alter-egos + "</h2>";
      html += '<h2>Power Stats ' + result.powerstats.combat + '</h2>';
      html += '<p>Connections ' + result.connections.relatives + '</p>';
      html += '<p>Appearance ' + result.appearance.gender + '</p>';
      html += '<p>Work ' + result.work.base + '</p>';
      // html += ' Profile <img src ' + result.image.url + '>';
    })
    // this is bad thing to do, injecting html like that into DOM
    // but let's leave this lesson for later stage
    // so, let's take this html and drop it onto the page
    document.getElementById('demo').innerHTML = html;
  }
}
<input type="search" id="mySearch" name="mySearch">
<button id="btn1">Search</button>
<div id="demo"></div>

答案 1 :(得分:0)

const value = document.getElementById('mySearch').value;

然后在您的api网址中使用此值。