使用数据库mysql和php过滤<select>和其他</select>

时间:2014-03-26 20:48:50

标签: jquery html filter option

我有一个表单,用户必须选择第一个<select>,它将过滤db上的第二个<select>,并在显示给用户之后。

我在一些网站上看过它,我想把它放在我的

第一个<select>

<select name="area" id="area">
    <option title="" value="">Select ...</option>
    <option value="1">First</option>
    <option value="2">Second</option>
    <option value="3">third</option>
</select>

如果我选择值为1的o选项,它将在MySQL上搜索id = 1

的所有行
SELECT * FROM tblarea WHERE id_prof = 1;

此结果将进行第二次选择

<select name="prof" id="prof">
    <option title="" value="">Select ...</option>
    <option value="1">1.1</option>
    <option value="2">1.2</option>
    <option value="3">1.3</option>
</select>

当查询正常运行时,它会显示在<select>“搜索...”

如果我错了,请帮助我,并给我一些想法。

由于

2 个答案:

答案 0 :(得分:1)

正如@dontHaveName建议的那样,使用看起来像这样的Ajax调用:

$('#area').on('change', function(e) {

  $.ajax({
    url: '/jobs/options/',
    type: 'POST',
    data: $(e.target).val(),
    dataType: 'html',
    success: function(opts) {
      $('#prof').html(opts);
    },
    error: function(xhr, status, err) {
     console.log(err); 
    }
  });

});

一些Ajax代码来自内存,所以如果你收到错误,请告诉我。

答案 1 :(得分:0)

如果您的选择对象上的项目很少,我建议您将所有可能性加载到JavaScript哈希中。在这种情况下,使用您的PHP程序来创建和填充此哈希。一旦用户更改了第一个选择元素,您就可以使用以下内容调用函数来填充第二个选择:

<html>
<body>

<script language=JavaScript>

//new hash is created
var area_prof = new Object();

// hash is being populated
area_prof["f"] = new Array("1.1","1.2","orange");
area_prof["s"] = new Array("2.1","2.2","white");
area_prof["t"] = new Array("3.1","3.2","3.3","hello world");

function populate()
{
var value=document.getElementById("area").options[document.getElementById("area").selectedIndex].value;

while (document.getElementById("prof").options[1])
    {
    document.getElementById("prof").options[1] = null;
    }

for (var i=0; i<area_prof[value].length; i++)
    {
    document.getElementById("prof").options[i+1] = new Option(area_prof[value][i],i);
    }
}

</script>

<select name="area" id="area" onChange=populate()>
    <option title="" value="">Select ...</option>
    <option value="f">First</option>
    <option value="s">Second</option>
    <option value="t">third</option>
</select>

<select name="prof" id="prof">
    <option title="" value="">Select ...</option>
</select>

</body>
</html>

但是如果你真的想要/需要创建另一个http请求来加载第二个组合框,那么你需要ajax:

https://api.jquery.com/jQuery.ajax/

致以最诚挚的问候,

爱德华多玛亚