jQuery之Ajax

我们需要注意的一点是:jQuery是函数式的写法。

下面我们来看一个关于Ajax的例子(注意:需要放到服务器下面进行一个运行):

GET方法进行一个请求:
index.html文件和getNews.php文件在同一个路径下,getNews.php文件中的内容为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
header('content-type:text/html;charset="utf-8"');
error_reporting(0);

$news = array(
array('title'=>'2020年全面建设小康社会的基本标准','date'=>'2020-1-6'),
array('title'=>'2020年欧洲足球锦标赛','date'=>'2020-1-6'),
array('title'=>'艺术拔尖生,2020年高招取消降分录取','date'=>'2020-1-6'),
array('title'=>'路虎宣布全新卫士2019年亮相 2020年正式上市','date'=>'2020-1-6'),
array('title'=>'工信部:2020年实现高级别自动驾驶特定场景应用','date'=>'2020-1-6'),
array('title'=>'2020年全面建设小康社会的基本标准','date'=>'2020-1-6'),
array('title'=>'2020年欧洲足球锦标赛','date'=>'2020-1-6'),
array('title'=>'艺术拔尖生,2020年高招取消降分录取','date'=>'2020-1-6'),
array('title'=>'路虎宣布全新卫士2019年亮相 2020年正式上市','date'=>'2020-1-6'),
);

echo json_encode($news);

index.html文件中的内容为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!DOCTYPE html>
<html lang="zh">

<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
</head>

<body>
<script>
$.ajax({
type: "GET", // 默认情况下type是一个GET值,可以不用写(但是还是建议写一下是GET还是POST,因为这样可以更清晰一些)。
url: "./getNews.php", // 规定发送请求的 URL。默认是当前页面。
success: function (data) { // 当请求成功时运行的函数
console.log(JSON.parse(data)); // data是一个JSON格式的字符串,需要用JSON.parse()方法将其转化为一个数组对象
},
async: true, // 布尔值,表示请求是否异步处理。默认是 true表示异步。
cache: true // 布尔值,表示浏览器是否缓存被请求页面。默认是 true表示要缓存。
});
</script>
</body>

</html>

在控制台中打印的内容如下图所示:
get方法异步加载打印出data的内容

POST方法进行一个请求:
index.html文件和post.php文件在同一个路径下,post.php文件中的内容为:

1
2
3
4
5
6
7
8
<?php 
header('content-type:text/html;charset="utf-8"');
error_reporting(0);

$username = $_POST['username'];
$age = $_POST['age'];

echo "名字: {$username}, 年龄: {$age}";

index.html文件内容为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!DOCTYPE html>
<html lang="zh">

<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
</head>

<body>
<script>
$.ajax({
type: "POST",
url: "./post.php",
success: function(data){
console.log(data) // 名字: daipi173, 年龄: 22
},
error: function(err){}, // 如果请求失败要运行的函数。
// data: "username=daipi173&age=22" // 规定要发送到服务器的数据。这种是标准形式,还可以写成一个对象形式{username:"daipi173",age:22}
data: {username:"daipi173",age:22} // 对象形式的写法
});
</script>
</body>

</html>