【问题标题】:How to get select value without submit button in PHP如何在没有提交按钮的情况下在 PHP 中获取选择值
【发布时间】:2020-09-20 08:45:50
【问题描述】:

我想在当前PHP文件中使用选择值,但是没有提交按钮,我该怎么做?

这是我的代码:

<?php

    $args = array(
                'orderby' => 'name', 
                'order' => 'ASC',
            );

    $pays = get_terms( 'pay', $args );
    $html = '<form action="#" method="post"><select name="selected_pay" id="selected_pay" >';

    foreach ($pays as $pay) {
        $html .= '<option value="'.$pay->name.'">'.$pay->name.'</option>';  
    }

    $html .= '</select></form>';
    echo $html;

?>

我想这样使用它:

<?php 

    if (isset($_POST['selected_pay'])) 
        echo $_POST['selected_pay'];
    else
        echo 'Please select a pay';

?>

【问题讨论】:

  • 如果没有某种提交功能,您将无法做到这一点。如果经典提交不适合您,您可以查找 ajax 提交
  • Philip G 是正确的,你需要 ajax。看这里:stackoverflow.com/questions/17591582/…
  • 但是我不知道ajax,你能给我一些想法吗?

标签: php html select


【解决方案1】:

您不需要提交按钮,但无论如何您需要向服务器发送 selected_pa​​y 的当前值。

例如,您可以在某些活动中这样做。 就像将鼠标悬停在某个元素上,甚至在某个特定时间;) 但是您必须定义事件 - 您想要发送/检查的时刻是什么时候,如果不是点击提交按钮。

我猜您真正想要的是在使用 AJAX 更改时发送/检查该值。您可以将 JQuery 与 onchange 事件一起使用。

jQuery('#selected_pay').change(function(){
   jQuery.post('script.php', {selected_pay: jQuery(this).val()}, function(data){
       jQuery(this).append(data); // show the result from script.php under the select element  
   })

});

【讨论】:

  • 你的意思是我必须使用 _POST['selected_pa​​y'] 编写我想在 script.php 中显示的内容?
  • 为什么是 script.php?我不明白这里。你能准确地给我解释一下吗
【解决方案2】:
<?php
    $args = array(
        'orderby'           => 'name', 
        'order'             => 'ASC',
    );
    $pays = get_terms( 'pay', $args );
?>
<form method="post">
<label for="combineForm">Un Pays</label>
<select name="selected_pay" id="selectedPay" onChange="form.submit()">
<?php 
    foreach ($pays as $pay) :  ?>
<option value="<?php echo $pay->name; ?>"><?php echo $pay->name; ?></option>
<?php endif; endforeach;?>

【讨论】:

    猜你喜欢
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 2016-08-29
    • 1970-01-01
    相关资源
    最近更新 更多