使用 jQuery 和 AJAX 的示例
HTML
<select id="selPrimary">
<option value="b.a">B.A</option>
<option value="b.com">B.Com</option>
<option value="b.b.a">B.B.A</option>
</select>
<select id="selSecondary"></select>
脚本
// jQuery doc.ready function
$(function() { // all "action" script goes in here
// Selects primary "select tag" by ID and assigns change event
$("#selPrimary").on("change", function(e) {
// Empty the options that might exist
// (from last choice in primary) and prep
// secondary for new options
$("#selSecondary").empty();
// .post is jQuery short hand for .ajax(..."type=post"
$.post("someFolder/someController.php", // this first param tells location of your php backend controller
function(data) { // this is the function that acts if the post is "successful"
$("#selSecondary").html(data); // fills secondary select tag with our new options
},
"json"); // this last param tells how to return the data
});
})
控制器(本例中为 PHP)
$retValue = "";
//Get Post Variables.
if (isset($_POST['selPrimary'])){
$value = $_POST['selPrimary'];
switch($value) {
case "b.a":
$retValue = '<option value='1'>1st</option><option value='2'>2nd</option<option value='3'>3rd</option>';
break;
case "whatev":
$retValue = '<option value='1'>1st</option><option value='2'>2nd</option<option value='3'>3rd</option>';
break;
}
}
echo json_encode($retValue);