我有两个链式选择框,第二个下拉列表根据第一个下拉列表的值填充,效果很好。我目前有一个php函数,当用户点击按钮时,它会检索并显示选择框的值。现在我遇到的挑战是因为他们必须单击按钮才能显示他们选择的选项,刷新页面但是我想要一种方法可以检索和显示所选的选项,这样用户就可以看到他们选择的内容而不刷新页面。我知道这可以使用ajax实现,但我是ajax的新手,我已经在线检查了很多类似的问题,但我不太明白如何使这项工作。对此有任何建议将非常感谢。请参阅下面我执行检索和显示所选值的php函数
function OutputCategory() {
if (isset($_POST['drop_2']) && ($_POST['btn_confirm']) && ($_POST['drop_1'])) {
$drop2 = $_POST['drop_2'];
$drop1 = $_POST['drop_1'];
$cat_name = mysql_query(sprintf("SELECT subcategory_name FROM subcategory WHERE subcategory_id = '%s'", mysql_real_escape_string($drop2)));
while ($cat_name1 = mysql_fetch_array($cat_name)) {
$cat_name2 = $cat_name1['subcategory_name'];
}
$cat = mysql_query(sprintf("SELECT category_name FROM category WHERE category_id = '%s'", mysql_real_escape_string($drop1)));
while ($cat1 = mysql_fetch_array($cat)) {
$cat_2 = $cat1['category_name'];
}
echo "You selected Category:";
echo $cat_2." >> ".$cat_name2;
}
elseif(isset($_POST['drop_1']) && ($_POST['btn_confirm'])) {
$drop1 = $_POST['drop_1'];
$cat = mysql_query(sprintf("SELECT category_name FROM category WHERE category_id = '%s'", mysql_real_escape_string($drop1)));
while ($cat1 = mysql_fetch_array($cat)) {
$cat_2 = $cat1['category_name'];
echo "You selected Category:";
echo $cat_2;
}
}
}
答案 0 :(得分:-2)
您需要将ajax调用绑定到select,如下所示:
$('#select1_id').on('change', function() {
$.ajax({
type: 'GET',
data: {
'select1_val': $(this).val()
},
url: 'some_page.php',
success: function( data ) {
$select2 = $('#select2_id');
$select2.empty();
$(data.options).each(function(i,option){
// append option to $select2
});
}
});
});
然后,在“some_page.php”上,有这样的事情:
if( $_GET['select1_val'] ) {
// get the select 2 vals, put them into an $array
json_encode(array('options' => $array )); exit;
}
......虽然这当然是一个非常简单的例子,但我相信你明白了这个想法
干杯,