简体   繁体   English

动态选择框

[英]Dynamic Select Box

I'm learning Php & Mysql. 我正在学习Php和Mysql。

I've a database(practice) with 2 table. 我有一个2表的数据库(练习)。 One is Category and other is sub-category. 一个是类别,另一个是子类别。

In my html form there are a list of select box data which is come from Category table. 在我的html表单中,有一个来自Category表的选择框数据列表。 So i need, if i select this list box, them another select box data will be appear from sub-category table which is related to Category table. 因此,我需要,如果我选择此列表框,则另一个选择框数据将从与类别表相关的子类别表中出现。 For example: 例如:

Category table 分类表

Id     Cat_name
1      O level  
2      A level.  

Sub-Category table: 子类别表:

id     Cat_id     Sub_name
1      1          O-level Math
2      1          O-level English
3      2          A-level Math
4      2          A-level English

Thanks in Advance. 提前致谢。

If you want this to be done seamlessly and efficiently without page reloads you will need to look into the Jquery Ajax function. 如果您希望无缝且高效地完成此操作而无需重新加载页面,则需要研究Jquery Ajax函数。 The way Ajax works is when someone makes a selection in the first box, it will send that data to a php script that can take the answer from the first box, run a mysql query, then return the new subcategories to the original page without having to reload the page. Ajax的工作方式是,当有人在第一个框中进行选择时,它将把数据发送到php脚本,该脚本可以从第一个框中获取答案,运行mysql查询,然后将新的子类别返回到原始页面而无需重新加载页面。

Example: In your test.php 示例:在您的test.php中

//On selection change state, call the ajax
$("#elementid").change(function() {
 var selection = $(this).children("option:selected");

  $.ajax({
    url: 'caller.php',
    dataType: 'json',
    data: 'selected='+selection,
    success: function(data) {
      //Fill the second selection with the returned mysql data
    }
  });
}

<select id="elementid">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

In your caller.php 在您的caller.php中

$selection = $_POST["selected"];
//Create an array to hold all the subcategories, say the array is called $sub
echo json_encode(array(success => $sub));
exit;

Please read up on Jquery.ajax 请在Jquery.ajax阅读

You will need Ajax to get this done, upon selecting a value in your first drop down, you send a request via ajaxnto another php file that will give you the resulting subcategories, based on the first selection. 您将需要Ajax来完成此操作,在第一个下拉列表中选择一个值后,您将通过ajaxn向另一个php文件发送请求,该文件将根据第一个选择为您提供最终的子类别。 Ajax will then insert this new data in your second dropdown. 然后,Ajax将在您的第二个下拉列表中插入此新数据。 You can also look into the post function from the jquery library, which will make this whole process even easier. 您还可以从jquery库中查看post函数,这将使整个过程更加容易。

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

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