博主信息
博文 21
粉丝 0
评论 0
访问量 19337
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
(1105)json 与 Ajax/get/post 异步请求实例
Yuming
原创
778人浏览过

json 与 Ajax/get/post 异步请求实例

实例演示 Ajax-post 的三种方式

  1. 表单键值对的方式
  1. // post请求
  2. const xhr = new XMLHttpRequest();
  3. //监听变化 xhr.readstatechange 变换0,1,2,3,4
  4. xhr.addEventListener("readystatechange", show, false);
  5. xhr.open("POST", "data/test2.php", true);
  6. const user = {
  7. name: "admin",
  8. email: "sdf",
  9. };
  10. let data = JSON.stringify(user);
  11. xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
  12. xhr.send(data);
  13. function show() {
  14. if (xhr.readyState === 4) {
  15. console.log(xhr.responseText);
  16. }
  17. }
  1. // post请求
  2. $data = key($_POST);
  3. $user = json_decode($data);
  4. echo '邮箱:'.$user->name.'密码:'.md5($user->email);

2.json 格式方式

  1. const xhr = new XMLHttpRequest();
  2. //监听变化 xhr.readstatechange 变换0,1,2,3,4
  3. xhr.addEventListener("readystatechange", show, false);
  4. xhr.open("POST", "data/test3.php", true);
  5. const user = {
  6. name: "admin",
  7. email: "sdf",
  8. };
  9. let data = JSON.stringify(user);
  10. xhr.setRequestHeader("content-type", "application/json;chaset=utf-8");
  11. xhr.send(data);
  12. function show() {
  13. if (xhr.readyState === 4) {
  14. console.log(xhr.responseText);
  15. }
  16. }
  1. // 以字节流的方法进行接收
  2. $data = file_get_contents('php://input');
  3. $user = json_decode($data,true);
  4. print_r($user);

3.不设置请求头方式

  1. const form = document.querySelector("form");
  2. const btn = document.querySelector("button");
  3. const xhr = new XMLHttpRequest();
  4. btn.addEventListener("click", handle, false);
  5. function handle() {
  6. xhr.addEventListener("readystatechange", show, false);
  7. // true为异步 (请求类型,请求地址,是否异步)
  8. xhr.open("POST", "./data/test4.php", true);
  9. let formData = new FormData(form);
  10. xhr.send(new FormData(form));
  11. }
  12. function show() {
  13. if (xhr.readyState === 4) {
  14. console.log(xhr.responseText);
  15. }
  16. }

实例演示 jsonp 跨域原理与实现

JSONP 跨域原理 生成一个标签,通过标签来进行跨域,注意此方式跨域请求只能为 GET

老师使用的是原生方式,我这里使用第三方库 jsonp 进行跨域
下面是我在 react 和 vue 中使用 jsonp 的请求调用百度 api 获取天气信息
请求之前需要安装 jsonp 的依赖

  1. /**
  2. * jsonp请求的接口请求函数
  3. */
  4. export const requstWeather = (city) => {
  5. /**
  6. * 新版的天气调用api用jsonp会出现问题 cord
  7. */
  8. // const url = `http://api.map.baidu.com/weather/v1/?district_id=440100&data_type=all&ak=bp7d90IIzRZr0fwqpVMibTv74lHIMibt`;
  9. const url = `http://api.map.baidu.com/telematics/v3/weather?location=${city}&output=json&ak=3p49MVra6urFRGOT9s8UBWr**`;
  10. return new Promise((resolve, reject) => {
  11. jsonp(url, {}, (err, data) => {
  12. if (!err) {
  13. resolve(data.results[0].weather_data[0]);
  14. }
  15. });
  16. });
  17. };
  • 数据获取结果如下图

下面是老师原生实现的

  1. const btn = document.querySelector("button");
  2. btn.addEventListener("click", createScript, false);
  3. function createScript(params) {
  4. let url = "http://blog.io/index.php?id=1&jsonp=show";
  5. const script = document.createElement("script");
  6. script.src = url;
  7. document.head.append(script);
  8. }
  9. function show(user) {
  10. console.log(user);
  11. }
  1. $users = [
  2. ['id'=>1,'name'=>'admin','email'=>'admin@php.cn'],
  3. ['id'=>2,'name'=>'zhangsan','email'=>'zhangsan@php.cn'],
  4. ['id'=>3,'name'=>'lisi','email'=>'lisi@php.cn'],
  5. ]
  6. $id = $_GET['id'];
  7. // js回调
  8. $callback = $_GET['jsonp'];
  9. foreach ($user as $users) {
  10. # code...
  11. if ($user['id']==$id) {
  12. # code...
  13. $result = $user
  14. break;
  15. }
  16. }
  17. $data = json_encode($result)
  18. echo '{$callback}({$data})'
批改老师:天蓬老师天蓬老师

批改状态:合格

老师批语:看来你是一定的基础的, 不错, 这次的培训, 你肯定是赚到了, 恭喜你
本博文版权归博主所有,转载请注明地址!如有侵权、违法,请联系admin@php.cn举报处理!
全部评论 文明上网理性发言,请遵守新闻评论服务协议
0条评论
作者最新博文
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号

  • 登录PHP中文网,和优秀的人一起学习!
    全站2000+教程免费学