json 与 Ajax/get/post 异步请求实例
实例演示 Ajax-post 的三种方式
- 表单键值对的方式
// post请求
const xhr = new XMLHttpRequest();
//监听变化 xhr.readstatechange 变换0,1,2,3,4
xhr.addEventListener("readystatechange", show, false);
xhr.open("POST", "data/test2.php", true);
const user = {
name: "admin",
email: "sdf",
};
let data = JSON.stringify(user);
xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
xhr.send(data);
function show() {
if (xhr.readyState === 4) {
console.log(xhr.responseText);
}
}
// post请求
$data = key($_POST);
$user = json_decode($data);
echo '邮箱:'.$user->name.'密码:'.md5($user->email);
2.json 格式方式
const xhr = new XMLHttpRequest();
//监听变化 xhr.readstatechange 变换0,1,2,3,4
xhr.addEventListener("readystatechange", show, false);
xhr.open("POST", "data/test3.php", true);
const user = {
name: "admin",
email: "sdf",
};
let data = JSON.stringify(user);
xhr.setRequestHeader("content-type", "application/json;chaset=utf-8");
xhr.send(data);
function show() {
if (xhr.readyState === 4) {
console.log(xhr.responseText);
}
}
// 以字节流的方法进行接收
$data = file_get_contents('php://input');
$user = json_decode($data,true);
print_r($user);
3.不设置请求头方式
const form = document.querySelector("form");
const btn = document.querySelector("button");
const xhr = new XMLHttpRequest();
btn.addEventListener("click", handle, false);
function handle() {
xhr.addEventListener("readystatechange", show, false);
// true为异步 (请求类型,请求地址,是否异步)
xhr.open("POST", "./data/test4.php", true);
let formData = new FormData(form);
xhr.send(new FormData(form));
}
function show() {
if (xhr.readyState === 4) {
console.log(xhr.responseText);
}
}
实例演示 jsonp 跨域原理与实现
JSONP 跨域原理 生成一个标签,通过标签来进行跨域,注意此方式跨域请求只能为 GET
老师使用的是原生方式,我这里使用第三方库 jsonp 进行跨域
下面是我在 react 和 vue 中使用 jsonp 的请求调用百度 api 获取天气信息
请求之前需要安装 jsonp 的依赖
/**
* jsonp请求的接口请求函数
*/
export const requstWeather = (city) => {
/**
* 新版的天气调用api用jsonp会出现问题 cord
*/
// const url = `http://api.map.baidu.com/weather/v1/?district_id=440100&data_type=all&ak=bp7d90IIzRZr0fwqpVMibTv74lHIMibt`;
const url = `http://api.map.baidu.com/telematics/v3/weather?location=${city}&output=json&ak=3p49MVra6urFRGOT9s8UBWr**`;
return new Promise((resolve, reject) => {
jsonp(url, {}, (err, data) => {
if (!err) {
resolve(data.results[0].weather_data[0]);
}
});
});
};
- 数据获取结果如下图
下面是老师原生实现的
const btn = document.querySelector("button");
btn.addEventListener("click", createScript, false);
function createScript(params) {
let url = "http://blog.io/index.php?id=1&jsonp=show";
const script = document.createElement("script");
script.src = url;
document.head.append(script);
}
function show(user) {
console.log(user);
}
$users = [
['id'=>1,'name'=>'admin','email'=>'admin@php.cn'],
['id'=>2,'name'=>'zhangsan','email'=>'zhangsan@php.cn'],
['id'=>3,'name'=>'lisi','email'=>'lisi@php.cn'],
]
$id = $_GET['id'];
// js回调
$callback = $_GET['jsonp'];
foreach ($user as $users) {
# code...
if ($user['id']==$id) {
# code...
$result = $user
break;
}
}
$data = json_encode($result)
echo '{$callback}({$data})'