下面是详细讲解 PHP 利用 AJAX 获取网页并输出的实现代码的攻略:
下面是详细讲解 PHP 利用 AJAX 获取网页并输出的实现代码的攻略:
1. 引入 jQuery 库
首先需要在 HTML 页面头部引入 jQuery 库。
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
2. 编写 AJAX 请求数据的代码
接下来需要编写通过 AJAX 请求数据的代码,可以使用 jQuery 的 $.ajax() 函数。
$.ajax({
url: 'http://example.com/',
method: 'GET',
success: function(response) {
// 请求成功后执行的代码
console.log(response);
},
error: function() {
// 请求出错时执行的代码
console.log('请求出错');
}
});
在上面的代码中,需要替换 url
的值为需要请求数据的网址,method
的值为请求方法,这里使用的是 GET 方法。请求成功后会执行 success
函数中的代码,请求出错时会执行 error
函数中的代码。
3. 输出请求到的数据
在成功获取到请求的数据后,需要将数据输出到页面中。这里使用 jQuery 的 .html()
函数将数据输出到指定的元素中。
$.ajax({
url: 'http://example.com/',
method: 'GET',
success: function(response) {
// 请求成功后执行的代码
$('#data').html(response);
},
error: function() {
// 请求出错时执行的代码
console.log('请求出错');
}
});
上面的代码中,使用了 #data
作为输出数据的元素选择器,并使用 .html()
函数将请求到的数据输出到该元素中。
示例1:使用 AJAX 请求并输出 Github 用户信息
<!DOCTYPE html>
<html>
<head>
<title>Github User Info</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>Github User Info</h1>
<div id="result"></div>
<script>
$(function() {
$.ajax({
url: 'https://api.github.com/users/octocat',
method: 'GET',
success: function(response) {
$('#result').html('<ul><li>Login: ' + response.login + '</li><li>Name: ' + response.name + '</li><li>Location: ' + response.location + '</li></ul>');
},
error: function() {
console.log('请求出错');
}
});
});
</script>
</body>
</html>
上面的代码中,使用了 Github 的 API 请求了 octocat
用户的信息,并将请求到的用户信息输出到页面中。
示例2:使用 AJAX 请求并输出本地文件内容
<!DOCTYPE html>
<html>
<head>
<title>Local File Content</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>Local File Content</h1>
<div id="result"></div>
<script>
$(function() {
$.ajax({
url: 'example.txt', // 本地文件名称
method: 'GET',
success: function(response) {
$('#result').html(response);
},
error: function() {
console.log('请求出错');
}
});
});
</script>
</body>
</html>
上面的代码中,从本地请求 example.txt
文件的内容,并将内容输出到页面中。
本文标题为:PHP 利用AJAX获取网页并输出的实现代码(Zjmainstay)
- laravel 自定义常量的两种方案 2023-03-02
- PHP7引入的"??"和"?:"的区别讲解 2023-01-05
- php提交post数组参数实例分析 2023-12-31
- PHP工厂模式简单实现方法示例 2022-10-18
- Laravel项目中timeAgo字段语言转换的改善方法示例 2023-02-13
- layui数据表格自定义每页条数limit设置 2023-03-12
- PHP defined()函数的使用图文详解 2023-01-30
- 搭建PhpStorm+PhpStudy开发环境的超详细教程 2023-05-02
- PHP iconv()函数字符编码转换的问题讲解 2023-01-04
- PHP8.0新功能之Match表达式的使用 2023-04-25