简体   繁体   中英

How to update a textbox with the result from a get Request

I have a simple web page designed to show the list of players when a certain team is selected. Currently my API can successfully return all of the players and display it it on the console log, but I am confused on how to you connect that with my div container.

My function returns all the player names as a list

<div class="card">
  <div class="card-header"> Player List</div>
  <div class="card-body">
    <label>Teams</label>
    <select id="playerDisplay" onChange="updatePlayerlist();">
      <option value=" ">Select a Team</option>
      <option value="Fractional">Giants</option>
    </select>
    <div class="col-sm-7">
      <label>Players</label>
      <div id="listPlayers"></div>
    </div>
  </div>
</div>
function updatePlayerslist() {
  var playerPick = $("#playerDisplay")[0].value;

  $.ajax({
    type: 'GET',
    url: APICALL,
    data: {
      'code': playerPick
    },
    success: function(list) {
      if (list.length === 0) {
        console.log(list);
        playerPick = list;
      } else
        console.log("EMPTY");
    }
  })
}

Given that you state:

My function returns all the player names as a list

I'm going to assume that the response is an array of strings. Therefore you can simply loop through that and create the new elements to append to the DOM. Try this:

function updatePlayerslist() {
  var playerPick = $("#playerDisplay").val(); // Note use of jQuery here

  $.ajax({
    type: 'GET',
    url: APICALL,
    data: {
      'code': playerPick
    },
    success: function(playerNames) {
      var html = playerNames.map(function(playerName) {
        return `<div>${playerName}</div>`;
      });
      $('#listPlayers').append(html);
    }
  })
}
function updatePlayerslist() {
  var playerPick = $("#playerDisplay")[0].value;

  $.ajax({
    type: 'GET',
    url: APICALL,
    data: {
      'code': playerPick
    },
    success: function(list) {
      if (list.length === 0) {
        console.log("EMPTY");
      } 

      // Construct the text to be displayed from the `list` data
      var textToDisplay = list.join(', ');

      // Update the html
      $('#listPlayers').html(textToDisplay);  
    }
  })
}

loop through the list and update the element by appending with jQuery

function updatePlayerslist(){
    var playerPick = $("#playerDisplay")[0].value;
    $.ajax({
        type: 'GET',
        url: APICALL,
        data: {
            'code': playerPick
        },
        success: function(list){
            console.log(list);
            list.forEach(value => {
                $("#listPlayers").append(value)
            })
        }
    })
}

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