📅  最后修改于: 2023-12-03 15:38:45.414000             🧑  作者: Mango
在 Web 开发中,通常使用 PHP 来处理服务器端的数据和业务逻辑,使用 HTML 来呈现页面内容。当需要在 HTML 页面中使用 PHP,就需要将外部的 PHP 文件链接到 HTML 中。
以下是将外部 PHP 文件链接到 HTML 的几种方式:
使用 PHP 的 include 函数可以在 HTML 页面中引入外部 PHP 文件。
<!DOCTYPE html>
<html>
<head>
<title>Link PHP File in HTML</title>
</head>
<body>
<?php include('file.php'); ?>
</body>
</html>
其中,file.php 是外部 PHP 文件的文件名。通过 include 函数,可以将外部 PHP 文件的内容嵌入到 HTML 页面中,从而实现相应的功能。
使用 AJAX 技术可以在不刷新整个页面的情况下更新页面部分内容。通过 AJAX 调用外部的 PHP 文件,可以实现局部更新页面内容的效果。
<!DOCTYPE html>
<html>
<head>
<title>Link PHP File in HTML with AJAX</title>
<script>
function loadPHP() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("output").innerHTML = this.responseText;
}
};
xhttp.open("GET", "file.php", true);
xhttp.send();
}
</script>
</head>
<body onload="loadPHP()">
<div id="output"></div>
</body>
</html>
通过 AJAX 调用 file.php 文件的方式与传统方式不同,需要使用 JavaScript 来完成。在页面加载完成后,调用 loadPHP 函数,该函数通过 AJAX 发送 GET 请求到 file.php 文件,获取服务器端返回的数据,并将其赋值给页面中 id 为 output 的 div 元素。
使用 PHP 的 header 函数可以将浏览器的当前位置重定向到外部的 PHP 文件。
<!DOCTYPE html>
<html>
<head>
<title>Link PHP File in HTML with redirect</title>
</head>
<body>
<?php
header('Location: file.php');
exit;
?>
</body>
</html>
通过 header 函数,将浏览器的当前位置重定向到 file.php 文件,从而实现跳转到外部 PHP 文件的效果。
综上所述,以上三种方式都可以将外部 PHP 文件链接到 HTML 中,具体使用方法根据实际需求选择。