有没有办法在不提交的情况下获取当前选择框选项的值


Is there a way to grab the current select box option's value without submitting?

我正在尝试为项目构建一些功能,但我坚持这样做:

我想从选择框选项中获取值,并在我的 php 脚本中使用它

问题是,我需要获取当前选定的选项,而无需用户发布数据。所以我怀疑这里需要一点 ajax,我是完全陌生的。

我举个例子,让事情更清楚:

        <select>
        <option value="United Kingdom">United Kingdom</option>
        <option value="Belarus">Belarus</option>
        <option value="Albania">Albania</option>
        </select>
  • 向用户显示一个选择框

  • 用户从下拉列表中选择"白俄罗斯">

  • 我需要能够获取值"白俄罗斯"并将其分配给 php 中的变量

我不知道如何在没有他们提交表格的情况下做到这一点。

任何帮助将不胜感激

谢谢

要使用 AJAX 将数据发送到 PHP 脚本:

$('select').on('change', function () {
    var val = $(this).val();
    if (val != '') {
        $.get('path/to/script.php', {'select-name' : val}, function (serverResponse) {
            //this is the callback for this AJAX request, the server has handled the request and anything output by your PHP script will be available in the `serverResponse` variable
        });
    }
});

请注意,.on() 是 jQuery 1.7 中的新功能,在本例中与.bind()相同。

您可以使用 jQuery ajax将数据部分提交到服务器。试试这个

$.ajax({
   url: "urlOfThePage",
   type: "POST",//Based on your requirement you can set it to GET/PUT etc
   data: {
      paramName: $("select").val();//this will get the selected value from the dropdown
   },
   sucess: function(){
     alert("Data submitted");
   }
});
<select id="my-select">
    <option value="United Kingdom">United Kingdom</option>
    <option value="Belarus">Belarus</option>
    <option value="Albania">Albania</option>
</select>

并使用jQuery获取值并将其传递给服务器:

var value = $("#my-select").val();
$.get('myscript.php', { select_value: value });