我是 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);
});
如何将选定的选项存储在变量中并将其发送回 PHP?没用过ajax,所以请尽量详细点,耐心点! :)
最佳答案
我更新了你的 jsfiddle
基本上您需要将此添加到您的代码中:
$.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/