Blogger Information
Blog 21
fans 0
comment 0
visits 14768
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
(1105)json 与 Ajax/get/post 异步请求实例
Yuming
Original
564 people have browsed it

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})'
Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:看来你是一定的基础的, 不错, 这次的培训, 你肯定是赚到了, 恭喜你
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post