0

我用materializecss創建了前端,並從aws獲取後端數據。在這裏,我想將aws中的項目列表顯示到我的前端下拉列表中。但是,它完全空白,並且在下拉列表中看不到任何數據。使用JavaScipt和Jquery在下拉列表中顯示後端數據

下面是我的代碼:

<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> 

當我第<p>標籤內試圖顯示它不下拉列表(即),它的工作原理。而且在console.log中,它顯示正確。

+1

移動'$( '選擇')material_select();'下面'data.Items.forEach((){});'塊 – adiga

+0

冷卻。有效。你能解釋一下嗎? –

+0

更新了具體細節的答案。 – adiga

回答

1

在您的代碼中$('select').material_select();位於$(document).ready(function() {之內。這意味着它將在加載DOM後立即運行。

但是docClient.scan是異步調用。根據服務器的不同,獲取數據並綁定到select需要一些時間。

所以,你應該您select填充後運行你的元素.material_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(); 
    } 
}); 
0

您正在運行courseList()以外的$(document).ready()函數。

在選擇框被初始化之前它可以運行嗎?

+0

這不提供一個問題的答案,應該是一個評論。請參閱[我應該何時評論?](https://stackoverflow.com/help/privileges/comment)。 一旦你有足夠的[聲望](https://stackoverflow.com/help/whats-reputation),你將可以在任何帖子上[評論](https://stackoverflow.com/help/privileges/comment);相反,[提供不需要提問者澄清的答案](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-c​​an- I-DO-代替)。 – Dwhitz

相關問題