简体   繁体   English

在HTML页面加载之前执行Javascript来填充下拉菜单

[英]Executing Javascript to populate a drop down before HTML page loads

I have 2 Drop Downs in a HTML form. 我有2个HTML格式的下拉菜单。 The first dropdown needs to be populated with a list of usernames present in the DATABASE. 需要使用数据库中存在的用户名列表填充第一个下拉列表。

Secondly, Depending upon the selection made in the first drop down, I then need to run another JS script to make another call to the DB to retrieve the list of associated addresses to that username. 其次,根据第一个下拉列表中的选择,然后我需要运行另一个JS脚本来再次调用数据库,以检索与该用户名关联的地址列表。

Can you please let me know whats the best way to achieve this objective? 您能告诉我实现此目标的最佳方法是什么吗? 1) How can I run a JSscript before the HTML form loads to return that list? 1)如何在HTML表单加载之前运行JSscript以返回该列表? 2) Should I get both the usernames and associated addresses in one Db call or just get the usernames first and then use onChange event on the first dropdown to execute the second call? 2)我应该在一个Db调用中同时获取用户名和相关地址,还是先获取用户名,然后在第一个下拉列表中使用onChange事件执行第二个调用?

Any code would be most appreciated. 任何代码将不胜感激。

Thanks 谢谢

well if you have all the info in same table then why dont you get all data in one go by querying as to the DB and then sort and put up data in the elements the way you want. 好吧,如果您将所有信息都放在同一个表中,那为什么不通过查询数据库一次就获得所有数据,然后按照所需的方式对数据进行排序和放入元素中。 the other way will need to query DB 2 times. 另一种方法将需要查询数据库2次。

here you can create your HTML to server call OR you can make HTML locally.
i have created options for selectbox at server and innerhtml to locally.

<select id="selectbox1" onchange="getData(this)"></select>
<select id="selectbox1"></select>

$(document).ready(function() {

$.ajax({
  url: 'http://localhost/getUsername.php',
  success: function(data) {
    $('#selectbox1').html(data);
    alert('Load was performed.');
  }
});

});

function getData(selData) {

$.ajax({
  url: 'http://localhost/getSecoundCall.php?id='+selData,
  success: function(data) {
    $('#selectbox2').html(data);
    alert('Load was performed.');
  }
});

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM