[英]Call a PHP function on a Bootstrap Modal using AJAX
我有使用PHP循環在頁面上回顯的用戶列表。 當我單擊每個用戶的名稱時,會彈出一個Bootsrap Modal,並顯示該用戶的更多詳細信息。 鏈接看起來像這樣。
<a href="#user" data-toggle="modal" data-id="{$user['id']}">UserName</a>
如您所見,我將用戶ID傳遞給Bootstrap模式,以便可以通過在Bootstrap模式中調用get_user_by_id()
來使用它來檢索用戶的其他信息。
模態看起來像這樣
<div class="modal fade" id="user">
<div class="modal-header">
<button class="close" data-dismiss="modal">×</button>
<h3>Modal header</h3>
</div>
<div class="modal-body">
<?php
$user = get_user_by_id($id);
?>
<input type="text" name="bookId" id="bookId" value=""/>
</div>
</div>
JS代碼是這樣的
$('#user').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget)
var id = button.data('id')
})
根據上面的JS代碼,我在var id
變量中有我的用戶ID。 但是,我無法想象如何將上述PHP函數的值用作參數。
有什么可能的辦法嗎?
我對問題進行了編輯,使其在AJAX方法上更加獨特,因為大多數答案都基於AJAX
PS:我是PHP和Bootstrap的新手。
您將要使用ajax運行PHP。 如@Tom所述,JavaScript在DOM中加載后無法訪問PHP。 PHP是服務器端語言,只能這樣訪問。
通過ajax連接到PHP后,您就可以使用返回內容加載div
。 只有在加載內容之后,才可以打開模態,否則將出現跳動的框外觀,然后才出現內容。
基本例子
$(".btn").click(function(){
// AJAX code here.
$.ajax(
....
success: function($data){
$('.target').html(data)
$("#myModal").modal('show');
}
);
});
這樣就不可能解決這個問題。 因為要使用PHP從服務器獲取數據,您必須向服務器請求數據,最好的唯一方法就是提交表單。 如此處所示,您希望以模式顯示數據,因此您需要異步進行處理。 所以您可以嘗試這樣-
//keep a button to show the modal for user details
<button class="detail" data-toggle="modal" data-target="#user_modal" data-id="<?= $user->id ?>">Detail</button>
//and using jQuery on the click of the above button post a form to your desire url
$(document).on("click", ".detail", function () {
var id = $(this).data('id');
$.ajax({
type: "POST",
url: "your/url",
data: { id: id},
success: function(data) {
//and from data you can retrive your user details and show them in the modal
}});
});
Bootstrap模態允許您加載遠程頁面,這正是您所尋找的...
<a href="userdata.php?uid=<?php echo $user['id']?>" data-target="#user" data-toggle="modal" data-id="{$user['id']}">UserName</a>
然后,模態變為:
<div class="modal fade" id="user" tabindex="-1" role="dialog" aria-labelledby="user" aria-hidden="true"><div class="modal-dialog modal-lg"><div class="modal-content"></div></div></div>
和userdata.php
<?php
$user_id = $_GET['uid'];
$user = get_user_by_id( $user_id );
?>
<div class="modal-header">
HEADER STUFF GOES HERE
</div>
<div class="modal-body">
USER INFO GOES HERE
</div>
<div class="modal-footer">
MODAL FOOTER HERE
</div>
Bootstrap modal有一個remote選項,但是在Bootstrap v3.3.0上已棄用 ,並將在v4中刪除。 您可以使用jQuery.load 。 例如
$( "#some-click" ).on('click', function() {
var userId = button.data('id'); //get user id here
//jQuery.load set html with modal and user details by id
$( "#user" ).load( "/not-here.php", { id:userId });
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.