文章目录
前言
使用class类对ajax进行简单的封装,以便于使用
一、使用class封装的过程
如何进行封装:
/*
url
data
dataType
*/
class axios {
static get (param = {}) {
// console.log(param);
param.method = 'get'
return axios.http(param)
}
static post (param = {}) {
param.method = 'post'
return axios.http(param)
}
static http (param) {
// console.log(param);
let { method, url, data, dataType = 'json' } = param;
//1 判断url是否为空
if (!url) {
throw new Error('判断不能为空')
}
// 2 处理data
let tmPparam = null;
if (data) {
// console.log(data);
tmPparam = [];
for (let attr in data) {
// console.log(attr);
// 以key=val的形式添加到数组中
tmPparam.push(`${attr}=${data[attr]}`)
}
// 3 以&分割为字符串
tmPparam = tmPparam.join('&');
// console.log(tmPparam);
// 4 get 请求则拼接参数到url上
if (method == 'get') {
url = url + '?' + tmPparam;
tmPparam = null;
}
}
return new Promise((resolve, reject) => {
// ajax的实现
let xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
xhr.send(tmPparam);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
let res = xhr.response;
if (dataType == 'json') {
res = JSON.parse(res)
}
// 成功
resolve(res)
} else {
reject(xhr.status)
}
}
}
})
}
}
二、如何使用已经封装的ajax
1.get方法
代码如下:
axios.get({
url: './01-ajax.php',
data: { name: 'zs', age: 18 },
dataType: ''
}).then(data => {
console.log(data);
}).catch(data => {
console.log(data);
})
2.post方法
代码如下:
axios.post({
url: './01-ajax.php',
data: { name: 'zs', age: 18 },
dataType: ''
}).then(data => {
console.log(data);
}).catch(data => {
console.log(data);
})
:
三、调用方法中用到的php文件
<?php
// 引入mysql文件
include('./mysql.php');
// 获取访问的方法
$fn = $_GET['fn'];
// add()
$fn();
// 添加数据的方法
function add(){
// echo 222;
$idea = $_GET['idea'];
$title = $_GET['title'];
$pos = $_GET['pos'];
// echo $idea;
// echo $pos;
// echo $title;
// die;
$sql = "insert into problem values(null,'$title','$idea','$pos')";
$res = query($sql);
echo $res;
}
// 获取数据的方法
function get(){
$sql = 'select * from problem';
$res = select($sql);
print_r(json_encode($res));
}
// 删除数据的方法
function del(){
$id = $_GET['infoId'];
$sql = 'delete from problem where id='.$id;
$res = query($sql);
echo $res;
}
//修改数据的方法
function update(){
$id = $_POST['id'];
$pos = $_POST['pos'];
$title = $_POST['title'];
$idea = $_POST['idea'];
$sql = "update problem set title='$title',pos='$pos',idea='$idea' where id=$id";
$res = query($sql);
echo $res;
}
?>
总结
我们应当注意的是,使用ajax时传递的参数以对象的形式传递,且索引的的url不能为空!