javascript - 将 jquery 变量发送回 PHP 并在 mySQL 中使用

标签 javascript php jquery mysql ajax

我是 ajax 的新手,但我读到 Ajax 是从 jQuery 存储变量并将其发送回 PHP 以使用它的唯一方法。

正如您在这个示例中看到的,我有一个从 MySQL 数据库填充的下拉列表:

$query = "SELECT * FROM my_gallery";
$execute = mysqli_query($link, $query); 

$results = mysqli_num_rows($execute);

if ($results!=0) {
    echo '<label>The galleries are: ';
    echo '<select id="galleries" name="galleries">';
    echo '<option value=""></option>';

    for ($i=0; $i<$results; $i++) {
        $row = mysqli_fetch_array($execute);
        $name = htmlspecialchars($row['galleryName']);

        echo '<option value="' .$name. '">' .$name. '</option>';
    }
   echo '</select>';
   echo '</label>';
}

使用 jQuery 我添加了 selected 属性:

$('#page').change(function(e) {
    e.preventDefault();
    var selectedOption = $(this).find('option:selected');
    $('#page option').removeAttr('selected');
    $(selectedOption).attr('selected','selected');
    var selectedOptionValue = $(selectedOption).val();
    var selectedOptionText = $(selectedOption).text();


    alert("You selected " + selectedOptionText + " Value: " + selectedOptionValue);
});

jsFiddle to see it in action

如何将选定的选项存储在变量中并将其发送回 PHP?没用过ajax,所以请尽量详细点,耐心点! :)

最佳答案

我更新了你的 jsfiddle

http://jsfiddle.net/sQ7Y9/2/

基本上您需要将此添加到您的代码中:

$.ajax({
      url: 'your url', //the url that you are sending data to
      type: 'POST', //the method you want to use can change to 'GET'
      data: {data : selectedOptionText}, //the data you want to send as an object , to receive in on the PHP end you would use $_POST['data']
      dataType: 'text', //your PHP can send back data using 'echo' can be HTML, JSON, or TEXT
      success: function(data){
       //do something with the returned data, either put it in html or you don't need to do anything with it
      }
});

关于javascript - 将 jquery 变量发送回 PHP 并在 mySQL 中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22075349/

相关文章:

javascript - 我需要一个脚本来在开关按钮打开时复制 <img> 标签,并在开关按钮关闭时删除 <img> 标签

javascript - 如何从 javascript 中的表单数据中删除选定的输入对象?

javascript - 简单的 javascript jQuery 代码在 Chrome 中工作,而不是在 Firefox、Safari、IE 中工作

jQuery 循环 ul li

javascript - 如何检测悬停时的前一个元素?

javascript - Fancybox 返回 "The requested content cannot be loaded. Please try again later."

php - 我如何使用 _GET 和 _POST?

php - 需要第二只眼睛来调试查询

php - 有很多 if 语句会降低 php 的渲染速度吗?

javascript - 如何使用 jQuery 为每一行的单选按钮添加计数?