
在 html 页面中通过 javascript 脚本显示 php 页面内容
在实际开发中,有时我们需要在 html 页面中动态加载和显示来自 php 页面中的数据或内容。以下介绍了如何通过 javascript 脚本调用显示一个 php 页面里的内容:
使用 ajax(asynchronous javascript and xml)
AJAX即“Asynchronous Javascript And XML”(异步JavaScript和XML),是指一种创建交互式网页应用的网页开发技术。它不是新的编程语言,而是一种使用现有标准的新方法,最大的优点是在不重新加载整个页面的情况下,可以与服务器交换数据并更新部分网页内容,不需要任何浏览器插件,但需要用户允许JavaScript在浏览器上执行。《php中级教程之ajax技术》带你快速
2114
ajax 是一种使用 javascript 在不重新加载整个页面情况下与服务器交换数据的技术。可以使用以下步骤通过 ajax 调用和显示 php 页面内容:
立即学习“PHP免费学习笔记(深入)”;
<html>
<head>
<script type="text/javascript">
// ajax 函数
function loadphp() {
var xhr = new xmlhttprequest();
xhr.open('get', 'a.php', true);
xhr.onload = function() {
if (xhr.status == 200) {
// 请求成功,处理来自 php 的响应
var data = json.parse(xhr.responsetext);
// 在 html 中显示 data
}
};
xhr.send();
}
</script>
</head>
<body onload="loadphp()">
<!-- 在此处显示数据 -->
</body>
</html><?php
// 获取数据
$data = ['key1' => 'value1', 'key2' => 'value2'];
// 将数据转换为 json
$json = json_encode($data);
// 发送响应
header('content-type: application/json');
echo $json;
?>// 处理 JSON 响应
function loadPHP() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'a.php', true);
xhr.onload = function() {
if (xhr.status == 200) {
var data = JSON.parse(xhr.responseText);
// 在 HTML 中显示 data
document.getElementById('target_div').innerHTML = data.key1 + ' ' + data.key2;
}
};
xhr.send();
}以上就是如何用JavaScript动态加载并显示PHP页面内容?的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号