使用 JavaScript 和 Jquery 在下拉列表中显示后端数据

Displaying the backend data in dropdown list using JavaScript and Jquery

我已经使用 materializecss 创建了前端,并且正在从 aws 获取后端数据。在这里,我想显示从 aws 到我的前端下拉列表 list.But 的项目列表,它是完全空白的,在下拉列表中看不到任何数据。

下面是我的代码:

<div class="row">
   <div class="input-field col s12">
      <select id="entries">
         <option value="0">- Select -</option>
      </select>
      <label>Course</label>
   </div>
</div>
<script>
   $(document).ready(function() {
       $('select').material_select();
       $('.datepicker').pickadate({
           selectMonths: true, // Creates a dropdown to control month
           selectYears: 15, // Creates a dropdown of 15 years to control year,
           today: 'Today',
           clear: 'Clear',
           close: 'Ok',
           closeOnSelect: false // Close upon selecting a date,
       });
   });

   $('#textarea1').val('New Text');
   $('#textarea1').trigger('autoresize');    

   courseList();

   function courseList() {

       AWS.config.region = 'us-west-2';
       AWS.config.update({
           accessKeyId: 'aaaaaaaaaaa',
           secretAccessKey: 'aaaaaaaaaaa'
       });
       var docClient = new AWS.DynamoDB.DocumentClient();
       let scanPar = {
           TableName: 'course',
           Limit: 100
       };

       docClient.scan(scanPar, function(err, data) {
           if (err) {
               console.log(err, null);
           } else {
               console.log(null, data);
               data.Items.forEach(function(courseEntry) {
                   $('#entries').append('<option>' + courseEntry.title + '</option>');                           
               });
           }
       });
   }
</script>

当我试图在 para <p> 标签内显示它时没有下拉列表(即),它起作用了。而且在console.log中也显示正确。

你 运行 courseList() 在你的 $(document).ready() 职能之外。

难道是运行在select框初始化之前?

在您的代码中 $('select').material_select();$(document).ready(function() { 中。这意味着它将在 DOM 加载后立即 运行。

但是docClient.scan是一个异步调用。根据服务器的不同,获取数据并绑定到 select 需要一些时间。

因此,您应该 运行 元素上的 .material_select() 填充 select 之后。

docClient.scan(scanPar, function(err, data) {
    if (err) {
        console.log(err, null);
    } else {
        console.log(null, data);
        data.Items.forEach(function(courseEntry) {
            $('#entries').append('<option>' + courseEntry.title + '</option>');                           
        });
        $('select').material_select();
    }
});