我有一个带有信息模式/按钮的选项,我想在选择更改时进行动态连接
我的代码就像这样
<select name="name_select" id="my_select">
<option value="1">Rossi</option>
<option value="2">Skunk</option>
<option value="3">Ceres</option>
</select>
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal"> Information </button>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Personal information</h4>
</div>
<div class="modal-body">
// query mysql
<?php (...) SELECT name, address, phone FROM table WHERE id = #my_select ?>
<input type="text" name="name" value="<?php echo $name ?>">
<input type="text" name="address" value="<?php echo $adress ?>">
<input type="text" name="phone" value="<?php echo $phone ?>">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
如何实现jquery post / get来解决这个问题?
答案 0 :(得分:2)
尝试使用ajax
此页面的脚本将是:
$(function () {
$(document).on("change", "#my_select", function () {
$.ajax({
url: 'path/to/ajaxfile.php',
type: 'GET',
dataType: 'json',
data: {id: $(this).val()},
})
.done(function(response) {
if (response.status) {
$("#myModal").find(".modal-body").html(response.html);
} else {
alert(status.message);
}
})
.fail(function(data) {
alert("Something went wrong please try again later.");
console.log(data.responseText);
});
});
});
和/ ajaxfile.php的路径代码:
/**
* Connect to the database and do other initialization if required.
*
* Assuming Procedual MySQLi.
*/
if (empty($_GET['id'])) {
echo json_encode(array("status" => false, "message" => "There is no User Selected."));
exit;
}
$id = mysqli_real_escape_string($connection, $_GET['id']);
$query = "SELECT name, address, phone FROM table WHERE id = '{$id}'";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
$inputs = '<input type="text" name="name" value="'. $row['name'] .'">
<input type="text" name="address" value="'. $row['address'] .'">
<input type="text" name="phone" value="'. $row['phone'] .'">';
echo json_encode(array("status" => true, "html" => $inputs));
exit;
} else {
echo json_encode(array("status" => false, "message" => "There is no user with that id."));
exit;
}
我希望这会有所帮助。