This question already has answers here:
html submit without submit button or JavaScript

(3个答案)


已关闭8年。




我想使用用户选择的选项值而不提交表单。这是我的HTML代码
Combo Box<br>
<select name="select1">
<option value="IVP" selected>IVP</option>
<option value="SURTEK">SURTEK</option>
<option value="GUITARTUNER">GUITARTUNER</option>
<option value="OTHER">OTHER</option>
</select>

我想将所选的选项值带到一个php变量中,以便根据选项值可以显示一组新的数据。
谢谢

最佳答案

正如其他人建议的那样,您应该使用AJAX。我建议研究一下AJAX调用的javascript/Jquery示例。

我猜您想根据用户选择的选项来修改网络的一部分,最好的方法是使用一个单独的PHP脚本来接收所选的选项(捕获在javascript/JQuery中)并返回您想要的新HTML显示。

例如在Jquery中获取选定的选项:

var selected_option_value=$("#select1 option:selected").val();

同样在Jquery中进行AJAX调用,使用POST传递值:
  $.post("script_that_receives_value.php", {option_value: selected_option_value},
      function(data){ //this will be executed once the `script_that_receives_value.php` ends its execution, `data` contains everything said script echoed.
          $("#place_where_you_want_the_new_html").html(data);
      }
  );

希望这可以帮助!

编辑:让我们对以上示例进行更多详细说明:

假设您有一个index.html页面,其中有问题中给出的<select name="select1">:

第一步是当某人选择一个选项时链接一个事件,该如何执行:

1-第一种方法:
<select name='select1' id='select1' onchange='load_new_content()'>

这样,当有人更改<select>列表的选定值时,将执行javascript函数load_new_content()。注意,我已经在标签中添加了id='select1',该标签用于在javascript/JQuery中搜索此元素,如果需要在javascript/JQuery中使用该标签,则应始终使用id属性。

2-第二种方式,使用JQuery链接事件:

为此,您应该在index.html的<script>内有一个<head>标记。在这个<script>标记内,您应该具有:
$(document).ready(function(){
      // everything here will be executed once index.html has finished loading, so at the start when the user is yet to do anything.
      $("#select1").change(load_new_content()); //this translates to: "when the element with id='select1' changes its value execute load_new_content() function"
});

无论您要使用哪种选项,现在都需要此load_new_content()函数。也应该在<script>标记的<head>标记内声明它,就像$(document).ready函数一样。
function load_new_content(){
     var selected_option_value=$("#select1 option:selected").val(); //get the value of the current selected option.

     $.post("script_that_receives_value.php", {option_value: selected_option_value},
         function(data){ //this will be executed once the `script_that_receives_value.php` ends its execution, `data` contains everything said script echoed.
              $("#place_where_you_want_the_new_html").html(data);
              alert(data); //just to see what it returns
         }
     );
}

现在剩下的唯一是这个script_that_receives_value.php:
<?php
     $selected_option=$_POST['option_value'];

     //Do what you need with this value, then echo what you want to be returned.

     echo "you have selected the option with value=$selected_option";
?>

关于php - 在不提交表单的情况下获取选项值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15153595/

10-12 12:33
查看更多