简体   繁体   中英

Using an AJAX call to asp page then using JSON data returned from page to populate a select box with options

I am trying to populate a select box based on JSON data returned from my ASP page: http://accdbmgr-001-site1.etempurl.com/ajax.asp

This is the data returned from the Server:

{
  "data": [{
    "Lastname": "Roussel",
    "Firstname": "Donald"
  }, {
    "Lastname": "Sabourin",
    "Firstname": "Manon"
  }, {
    "Lastname": "Kelly",
    "Firstname": "Bruce"
  }]
}

However, for some reason it just doesn't seem to be able to add my JSON data into the select box. I'd like for the options to appear as: Lastname, FirstName

<div id="test"></div>
<form>
  <select id="select1"></select>
</form>
$(document).ready(function() {
  $.get('http://accdbmgr-001-site1.etempurl.com/ajax.asp', {
    category: 'client',
    type: 'premium'
  }, function(data) {
    alert("success")
    //$("#test").html(data)
    var obj = JSON.parse(data);
    for (i in obj) {
      $('#select1').append(new Option(obj[i].Firstname, obj[i].Lastname));
    }
  });
});

The main issue is because you're looping through obj , when you instead need to loop through the obj.data array.

Also note that you can use map() to build an array of strings which you can then append() once to make the logic more succinct and more performant.

Finally your code is currently creating an option element with Firstname as the text of the element, and Lastname as the value . If you want the text to be in Lastname, Firstname format you need to set the text to that explicitly. Try this:

 var obj = { "data": [{ "Lastname": "Roussel", "Firstname": "Donald" }, { "Lastname": "Sabourin", "Firstname": "Manon" }, { "Lastname": "Kelly", "Firstname": "Bruce" }] } var options = obj.data.map(function(item) { return `<option>${item.Lastname}, ${item.Firstname}</option>`; }); $('#select1').append(options);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="test"></div> <form> <select id="select1"></select> </form>

Also note that JSON.parse() is not needed if you set dataType: 'json' on the request, or use $.getJSON()

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