在 html 页面中通过 javascript 脚本显示 php 页面内容
在实际开发中,有时我们需要在 html 页面中动态加载和显示来自 php 页面中的数据或内容。以下介绍了如何通过 javascript 脚本调用显示一个 php 页面里的内容:
使用 ajax(asynchronous javascript and xml)
ajax 是一种使用 javascript 在不重新加载整个页面情况下与服务器交换数据的技术。可以使用以下步骤通过 ajax 调用和显示 php 页面内容:
- 创建 html 页面:建立一个 html 页面,其中包含一个 <script> 标签,如下所示:</script>
<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 页面:在 a.php php 页面中,编写代码以生成 json 响应数据。
<?php// 获取数据$data = [‘key1’ => ‘value1’, ‘key2’ => ‘value2’];// 将数据转换为 json$json = json_encode($data);// 发送响应header(‘content-type: application/json’);echo $json;?>
- 解析 json 响应:在 html 页面的 javascript 函数中,解析来自 php 的 json 响应并更新 html 内容。
// 处理 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 中显示 datadocument.getElementById(‘target_div’).innerHTML = data.key1 + ‘ ‘ + data.key2; } }; xhr.send();}
以上就是如何用JavaScript动态加载并显示PHP页面内容?的详细内容,更多请关注范的资源库其它相关文章!
转载请注明:范的资源库 » 如何用JavaScript动态加载并显示PHP页面内容?