简体   繁体   English

根据另一个列表框值将值列表加载到列表框

[英]load list of values to the listbox based on another listbox value

load different list of values(from a database) to listbox when changing another listbox value for ex: First list box : -select grade- 在更改ex的另一个列表框值时,将不同的值列表(从数据库)加载到列表框:第一个列表框:-select grade-

Second List box : -select Subject- 第二个列表框:-选择主题-

Please Help Thank You 请帮忙谢谢

The basic idea is to submit that data to the server (either by POST back, or AJAX), and then respond with the data. 基本思想是将数据提交到服务器(通过POST back或AJAX),然后用数据响应。

<select id="mySel" onChange="sendData()">

What I've done there is added a javascript function to be called every time the drop down value has changed. 我所做的事情是添加了一个javascript函数,每次下拉值更改时都会调用该函数。

function sendData() {
    $.post("processData.php", {selected: $(this).val()}, updateData(data));
}

This is a skeleton of the function I'd write for the select onChange event. 这是我为select onChange事件编写的函数的框架。 I've skipped a step or two here and used jQuery to help create an AJAX request back to the server. 我在这里跳过了一两个步骤,并使用jQuery帮助创建了一个返回服务器的AJAX请求。 I will be calling my php script processData.php to help process which element was selected. 我将调用我的PHP脚本processData.php来帮助处理选择了哪个元素。 The {} contain the data I want to send to the server, in this case the selected value. {}包含我要发送到服务器的数据,在这种情况下为所选值。 And Finally what to do once I get data back from the server. 最后,一旦我从服务器取回数据,该怎么办。

Now I'd be in my php file and able to process the data I took in and run my query to get the new data. 现在,我将进入我的php文件,并能够处理接收的数据并运行查询以获取新数据。 Once done I simply json_encode the data and respond with it. 完成后,我只需对数据进行json_encode并进行响应即可。

Now back in the javascript world my UpdateData function is automatically called and passed the json data. 现在回到javascript世界,我的UpdateData函数将自动被调用并传递json数据。

function updateData(data) {
    var select = '<select name="sel2">';
    $().each(data, function(index, val){
        select += '<option name="'+ index+ '">'+ value+ '</option>';
    });
    $("#mySel").parent.append(select);
}

That would allow me to generate a new select list from the returned data (assuming a key/value paired array in json). 那将允许我从返回的数据生成一个新的选择列表(假设json中的键/值配对数组)。

I haven't actually tested any code and it's designed to be more of a guide and pseudo-code. 我实际上还没有测试任何代码,它的目的更多是为了指导和伪代码。

当用户从一个选择元素中选择一个值时,发送XMLHttpRequest以获取填充第二个选择元素的数据。

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

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