[英]How do I include content from an external PHP page into a DIV with onlick event?
我有一個這樣的形式:
<button type="button" name="viewRecords" id="viewRecords" class="activeButton" onClick=
"<?php include ("") ?>"
我希望在單擊按鈕時使用來自外部PHP文件的內容填充div。
<div id="admin-content">
<?php include ("view-records.php");?>
</div>
有沒有辦法做到這一點?
由於PHP是在頁面生成時運行的,而不是響應用戶界面事件的,因此無法直接使用PHP進行此操作(除非您當然加載了新頁面)。
閱讀Ajax,並使事情變得更輕松,請使用jQuery,盡管可以使用其他庫。
例如與jquery / Ajax一樣簡單
// Javascript
function success(data) {
// Assuming you return raw HTML from the ajax call...
$('#admin-content').html(data); // inserts the html into the div.
}
$.ajax({
url: url,
data: data, // URLencoded query string (google encodeURIComponent() if you don't know this)
success: success,
dataType: 'html'
});
了解更多: http : //api.jquery.com/jquery.get/
您可以使用jQuery的.post方法來實現。 確保在網頁的頂部包含jQuery。
$("#viewRecords").click(function() {
$.post( "view-records.php", function( data ) {
$( "#admin-content" ).html( data );
});
});
有關JQuery .load方法的更多信息,請參見此處 。
另外,如果您想避免使用其他人提供的jQuery解決方案(也很好),那么您可以在純JavaScript中獲得相同的結果(只需將此代碼放在<head>
標記中的某個位置):
<script type="text/javascript">
function viewRecords() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("admin-content").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "view-records.php", true);
xmlhttp.send();
}
</script>
然后在按鈕的onClick處理程序上調用該函數:
<button type="button" name="viewRecords" id="viewRecords" class="activeButton" onClick="viewRecords();" value="View Records" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.