如何将来自外部 PHP 页面的内容包含在带有 onlick 事件的 DIV 中

How do I include content from an external PHP page into a DIV with onlick event?

本文关键字:包含 DIV 事件 onlick 将来 何将来 PHP 外部      更新时间:2023-09-26

我有一个包含这个的表单:

<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" />