Bro*_*val 2 php foreach select
大陆表
国家表
这是我的表中的数据,我从大陆表和国家/地区表中获取所有数据,如下所示
<select name="continent" class='required InputBox'>
<?php echo "<option value=''></option>";
foreach (Contintent() as $value) {
echo "<option id='" . $value[ 'sysid'] . "' value='" . $value[ 'name'] . "'>" . $value[ 'name'] . "</option>"; } ?>
</select>
Run Code Online (Sandbox Code Playgroud)
这是为了国家
<select name="country" class='required InputBox'>
<?php echo "<option value=''></option>";
foreach (Country() as $value) {
echo "<option id='" . $value[ 'sysid'] . "' value='" . $value[ 'name'] . "'>" . $value[ 'name'] . "</option>"; } ?>
</select>
Run Code Online (Sandbox Code Playgroud)
我想知道如何做到这一点,当我选择大陆(例如亚洲)时,县可用的选项将是仅亚洲的国家,即日本和中国。此后我还有另一个表,即城市,但如果我得到这里的逻辑,我可以将其应用到城市。任何想法表示赞赏
“更新”
在这里发现了一些东西
我不熟悉的一个是ajax,任何人都可以尝试解释它是如何工作的,我想知道如何将这个javascript片段中的选择的id传递到我的php函数页面,这里是片段..
$('.continent').change(function() {
var id = $(this).find(':selected')[0].id;
//alert(id);
$.ajax({
type:'POST',
url:'../include/functions.php',
data:{'id':id},
success:function(data){
// the next thing you want to do
console.log(data);
alert(id);
}
});
});
Run Code Online (Sandbox Code Playgroud)
在我的函数中 php
function Country(){
if(isset($_POST['id'])){
echo $_POST['id'];
}
}
Run Code Online (Sandbox Code Playgroud)
问题是 id 的值没有传递,我如何将它传递到 function.php 我在这里有点不知道。它发生在success:function(data){
我接下来要做什么吗?
FYI
警报没问题,它已经获取了大陆的 id,只是没有传递给 function.php 并且 console.log 不写入任何内容,当我将 url 更改为主页时,console.log 中选择所在的页面返回主页代码。
正如所说,您可以使用ajax。有一种静态的非ajax方法可以做到这一点,但从长远来看这种方法更好。
基本上,您使用该 jQuery 所做的就是监听大陆选择框中的更改,当发生更改时,您向服务器发出请求:“给我该大陆内的所有国家/地区”。您应该为此拥有一个数据库,或者您可以将它们映射到静态对象中以进行测试。
$('.continent').change(function() {
var id = $(this).val(); //get the current value's option
$.ajax({
type:'POST',
url:'<path>/getCountries',
data:{'id':id},
success:function(data){
//in here, for simplicity, you can substitue the HTML for a brand new select box for countries
//1.
$(".countries_container").html(data);
//2.
// iterate through objects and build HTML here
}
});
});
Run Code Online (Sandbox Code Playgroud)
这当然会让您countries_container
在 HTML 中添加类似的内容,并在其中呈现select
:
<div class="countries_container"></div>
Run Code Online (Sandbox Code Playgroud)
现在,在实际的 PHP 代码服务器端 (getCountries) 中,您可以执行以下操作:
$id = $_POST['id'];
if(isset($id) && <other validations>)){
// 1. your query to get countries from a given continent
// and for each result you can build the HTML itself
// 2. OR, a better solution is to return an Object and then in the
// success:function(data){ } iterate through it
}
Run Code Online (Sandbox Code Playgroud)
这段代码绝对可以改进,但我试图以一种可以理解的方式解释它。
另外,您应该检查:
Jquery ajax 使用 json 响应数据填充下拉列表
请记住,这些是谷歌搜索的第一个结果,因此,下次,尝试在堆栈溢出本身中搜索以避免重复的问题。
归档时间: |
|
查看次数: |
19627 次 |
最近记录: |