如何在不刷新页面和不单击“发送”按钮的情况下从下拉选择中向 MYSQL 发送值


How could I send a value to MYSQL from a dropdown selection without refresh page and without click the "send" button?

在PHP页面中,我有一个简单的选择,其中包含一些这样的值:

<div class="container">      
  <section>
    <select>
      <option value="" disabled selected>Select an activity</option>
      <option value="1">1</option>
      <option value="2">2</option>
      ...
    </select>
  </section>      
</div>

我有一个数据库 MYSQL 来存储选择的value,如下所示:

表名 = user_favorite,有 2 列,分别称为 itemsvalues

项目
项目1 值1      
      项目2 值2      
      等。

当用户从下拉列表中选择一个项目时,我希望将所选value(在values列内)自动发送到MYSQL,而无需单击发送按钮。是否可能以及如何实现?

正如@NishantSolanki所说,你应该使用Ajax。下面是一个使用 jQuery 的示例。

文件:

<div class="container">      
   <section>
       <select id="options">
           <option value="" disabled selected>Select an activity</option>
           <option value="1">1</option>
           <option value="2">2</option>
       </select>
   </section>      
</div>
<script type="text/javascript">
    jQuery(document).ready(function(){
        jQuery("#options").on("change", function(){ //listen when the option change   
            var optionValue = jQuery(this).val();   //get the new value
            $.ajax({
                url: "fileWhichSaveTheValue.php", //php file which recive the new value and save it to the database
                data: { "newValue": optionValue },  //send the new value
                method: "POST"                    //use POST method
            });
        });
    });
</script>

PHP文件:

$newValue = $_POST["newValue"]; //if you used POST method on the javascript, you have to use $_POST here to get the data

//HERE YOUR MYSQL CONNECTION AND YOUR QUERY FOR SAVING THE VALUE

在选择

<?php
    if($_POST){
     $item = $_POST['item'];
     $link = mysql_connect('host', 'username', 'password');
     mysql_select_db('database_name', $link);
     //write your sql query to enter into table
    }
 ?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<div class="container">      
  <section>
    <select onchange="save_record(this.value);">
      <option value="" disabled selected>Select an activity</option>
      <option value="1">1</option>
      <option value="2">2</option>
      ...
    </select>
  </section>      
</div>

<script type="text/javascript">
function save_record(item){
    //call an ajax here to post item 
    $.post( "your_php_page_name.php",
      {item:item}, 
      function( data ) {
        // do something after ajax result
      });
}
</script>

在您的 php 页面上,您可以通过$_POST变量检索帖子数据

相关文章: