jQuery封装ajax的使用方法
1.什么是jQuery
jQuery是一个简洁而快速的JavaScript库,里面定义了各种函数方法,可以直接使用,可以使用很多功能。
jQuery的三大优点:
- 强大的选择机制—方便获取标签对象
- 优质的隐式迭代—默认对数组中的所有标签进行操作
- 无所不能的链式编程—再复杂的操作,一行代码搞定
2.jQuery封装的ajax请求有3种
jQuery封装的ajax请求——get方式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>get请求</h1>
<button>请求</button>
<script src="../jquery.min.js"></script>
<script>
$('button').click(function(){
$.get({
// 对 url 地址的PHP文件发起请求
url : './get.php',
// 请求时携带参数,参数以对象形式定义
data : {name:'张三' , pwd:123456},
// 没有设定 dataType 参数,res中的响应体
// 后端给什么,res中,就存储什么
// 设定 dataType : 'json', 会自动解析响应体json串
dataType : 'json',
// 请求成功时,执行的函数
// 函数的参数,存储响应体
// 自定义形参 res 中 存储的就是响应体
success : function(res){
console.log(res)
}
})
})
</script>
</body>
</html>
get方式php
<?php $name = $_GET['name']; $pwd = $_GET['pwd']; $arr = [ 'msg' => '您请求的方式是get,我就不查询数据库了,直接返回参数内容', 'data' => [ 'name' => $name, 'pwd' => $pwd, ] ]; echo json_encode($arr);
jQuery封装的ajax请求——post方式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>post请求</h1>
<button>请求</button>
<script src="../jquery.min.js"></script>
<script>
$('button').click(function(){
$.post({
// 对 url 地址的PHP文件发起请求
url : './post.php',
// 请求时携带参数,参数以对象形式定义
data : {name:'张三' , pwd:123456},
// 没有设定 dataType 参数,res中的响应体
// 后端给什么,res中,就存储什么
// 设定 dataType : 'json', 会自动解析响应体json串
dataType : 'json',
// 请求成功时,执行的函数
// 函数的参数,存储响应体
// 自定义形参 res 中 存储的就是响应体
success : function(res){
console.log(res)
}
})
})
</script>
</body>
</html>
post方式php
<?php $name = $_POST['name']; $pwd = $_POST['pwd']; $arr = [ 'msg' => '您请求的方式是post,我就不查询数据库了,直接返回参数内容', 'data' => [ 'name' => $name, 'pwd' => $pwd, ] ]; echo json_encode($arr);
jQuery封装的ajax请求——ajax方式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>ajax请求</h1>
<button>请求</button>
<script src="../jquery.min.js"></script>
<script>
const obj = {};
$('button').click(function(){
$.ajax({
// 对 url 地址的PHP文件发起请求
url : './get.php',
// 请求方式,不写就是,默认值get.
type: 'get',
// data传参参数
data : {name:'张三',pwd:123456},
// dataType, 设定 json 解析响应体的json串
dataType : 'json',
success : function(res){
console.log(res);
console.log(this);
},
// 不常用的
// async : false, // 设定异步
// 请求成功不执行,请求失败才执行
error : function(res){
console.log(res)
},
// timeout : 1, // 超时报错,但是必须是异步执行
cache : false, // 如果是不缓存,会在数据后有一个 _数值 的时间戳
// 告诉程序,这个结果的获取时间
context : obj , // this默认指向 ajax对象 , 可以设定this的指向
})
console.log('我是同步执行的程序');
})
</script>
</body>
</html>
ajax方式php
<?php $name = $_GET['name']; $pwd = $_GET['pwd']; $arr = [ 'msg' => '您请求的方式是get,我就不查询数据库了,直接返回参数内容', 'data' => [ 'name' => $name, 'pwd' => $pwd, ] ]; echo json_encode($arr);

浙公网安备 33010602011771号