PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

博客列表 > ajax跨域、json及常用数组函数

ajax跨域、json及常用数组函数

我是贝壳
我是贝壳 原创
2021年01月16日 21:02:32 562浏览

ajax跨域、json及常用数组函数

1 ajax

相关概念解析:
(1)同步:前端发请求,必须等到后端响应完成,才允许发送另一个请求
异步:前端发请求后,不需等待后端响应结果继续执行,后端响应完成通过事件通知前端处理
(2)XMLHttpRequest对象
a:创建xhr对象:const xhr = new XMLHttpRequest();
b:配置xhr参数:xhr.open(type,url);
c:处理xhr响应:xhr.onload = () => {};
d:发送xhr请求:xhr.send();
(3)xhr对象常用属性
responseType:设置响应类型
response:响应正文
(4)xml对象常用方法
open(type,url):配置请求参数
send(data/null):发送请求,默认值是null
(5)xhr对象常用事件
load():请求成功
error():请求失败

1.1 get请求

代码前准备:
搭建hello服务器,个人用的是免费工具pupstudy,前端html与后端php在同一个目录文件

前端页面代码:

  1. <button>ajax-get</button>
  2. <p></p>
  3. //将script脚本写在前端页面里
  4. <script>
  5. const btn =document.querySelector("button");
  6. btn.onclick = () => {
  7. //严格按照xhr对象的四个步骤走
  8. //1 创建xhr对象
  9. const xhr = new XMLHttpRequest();
  10. //2 配置xhr参数,open(type:访问方式,url:访问目标地址),
  11. xhr.open("get","test1.php?id=2");
  12. xhr.responseType = "json";
  13. //3 处理xhr响应:
  14. //成功
  15. xhr.onload = () => {
  16. console.log(xhr.response);
  17. //dom:将响应结果渲染到页面中
  18. let user = `${xhr.response.name}(${xhr.response.email})`;
  19. document.querySelector("p").innerHTML = user;
  20. };
  21. xhr.onerror = () => console.log("Error");
  22. };
  23. //4 发送xhr请求
  24. xhr.send(null);
  25. </script>

后端代码

  1. //使用二维数组模拟用户数据表信息
  2. $users = [
  3. ['id'=>1, 'name'=>'天蓬','email'=>'tp@php.cn','password' => md5('123456')],
  4. ['id'=>2, 'name'=>'灭绝','email'=>'mj@php.cn','password' => md5('abc123')],
  5. ['id'=>3, 'name'=>'西门','email'=>'xm@php.cn','password' => md5('abc888')],
  6. ];
  7. // 查询条件
  8. $id = $_GET['id'];
  9. //在id组成的数组中查询是否存在指定的id,并返回对应的键名
  10. //array_column($users,'id')在users数据里面拿出id一列
  11. //array_search($id,array):在array数组中查找$id
  12. $key = array_search($id,array_column($users,'id'));
  13. //根据键名返回指定的用户信息
  14. echo json_encode($users[$key]);

完整代码的输出:

页面上一个value值为ajax-get的按钮,点击后,向后端传递id=2,后面在users数据中搜索id=2的数据,打到后返回正文显示:灭绝(mj@php.cn

1.2 post请求

通常用于提交表单数据,前端html与后端php在同一个目录文件

FormData是表单数据构造器
(1)append(name,value):添加表单数据
(2)delete(name):删除表单数据

示范代码:
前端:

  1. <div class="login">
  2. <h3>用户登录</h3>
  3. <form action="" onsubmit="return false">
  4. <label for="email">邮箱:</label>
  5. <input type="email" name="email" id="email" />
  6. <label for="password">密码:</label>
  7. <input type="password" name="password" id="password" />
  8. <button>提交</button>
  9. <span class="tips"></span>
  10. </form>
  11. </div>
  12. //将script脚本写在前端页面里
  13. //获取表单数据
  14. <script>
  15. const form = document.querySelector(".login form");
  16. const btn = document.querySelector(".login button");
  17. const tips = document.querySelector(".tips");
  18. btn.onclick = () => {
  19. //严格按照xhr对象的四个步骤走
  20. //1 创建xhr对象
  21. const xhr = new XMLHttpRequest();
  22. //2 配置xhr参数,open(type:访问方式,url:访问目标地址),以post方式,访问后端test2.php
  23. xhr.open("post","test2.php");
  24. //3 处理xhr响应:
  25. //成功
  26. xhr.onload = () => (tips.innerHTML = xhr.response);
  27. //4 发送xhr请求,需以表单的形式发送
  28. xhr.send(new FormData(form));
  29. </script>

后端代码:

  1. //使用二维数组模拟用户数据表信息
  2. $users = [
  3. ['id'=>1, 'name'=>'天蓬','email'=>'tp@php.cn','password' => md5('123456')],
  4. ['id'=>2, 'name'=>'灭绝','email'=>'mj@php.cn','password' => md5('abc123')],
  5. ['id'=>3, 'name'=>'西门','email'=>'xm@php.cn','password' => md5('abc888')],
  6. ];
  7. //将通过post获取的数据保存到临时变量中
  8. $email = $_POST['email'];
  9. $password = md5($_POST['password']);
  10. //使用数组过滤中器查询是否存在指定的用户并返回结果
  11. //php中function ($user) use ($email,$password)是php中匿名函数闭包的写法,匿名函数需要使用到外部变量
  12. $res = array_filter($users,function($user) user ($email,$password){
  13. return $user['email'] === $email && $user['password'] === $password;
  14. });
  15. //将结果作为请求响应返回前端
  16. echo count($res) ===1 ? '验证成功' : '验证失败';

完整代码的输出:

页面上有一个表单输入框,提交后,下方提示输入内容,只有输出的邮箱和密码同时正确时,页面才会提示验证成功或者验证失败

1.3 跨域get请求

代码前准备:
创建两个服务器hello和world,前者存放前端代码,后者存放后端代码,个人用的是phpstudy。

前端服务器hello的前端代码:

  1. <button>ajax-get-cors</button>
  2. <p></p>
  3. <script>
  4. //获取按钮对象
  5. const btn = document.querySelector("button");
  6. btn.onclick = () => {
  7. //1 创建xhr对象
  8. const xhr = new XMLHttpRequest();
  9. //2 配置xhr参数
  10. xhr.open("get","http://world.io/cors1.php");
  11. //3 处理xhr响应
  12. xhr.onload = () => {
  13. document.querySelector("p").innerHTML = xhr.response;
  14. };
  15. //4 发送xhr请求
  16. xhr.send(null);
  17. };
  18. </script>

后端服务器world的cors1.php处理代码:

  1. // 浏览器默认关闭跨域访问,故需要在服务器端开启跨域许可
  2. // header('Access-Control-Allow-Origin: http://hello.io');
  3. // *: 任何来源
  4. header('Access-Control-Allow-Origin: *');
  5. echo 'CORS:跨域请求成功';

最终输出:页面上有一个ajax-get-cors的按钮,点击后,下方显示CORS:跨域请求成功

1.4 跨域post请求

前端服务器hello的页面代码:

  1. <button>ajax-post-cors</button>
  2. <p class="tips"></p>
  3. <script>
  4. //获取按钮对象
  5. const btn = document.querySelector("button");
  6. const tips = document.querySelector(".tips");
  7. btn.onclick = () => {
  8. //1 创建xhr对象
  9. const xhr = new XMLHttpRequest();
  10. //2 配置xhr参数,opst方式访问cors2.php xhr.open("post","http://world.io/cors2.php");
  11. //3 处理xhr响应
  12. xhr.onload = () => (tips.innerHTML = xhr.response);
  13. //4 发送xhr请求
  14. let formData = new FormData();
  15. formData.append("email","admin@php.cn");
  16. formData.append("password","123456");
  17. xhr.send(formData);
  18. };
  19. </script>

后端服务器world的cors2.php代码:

  1. header('Access-Control-Allow-Origin:*');
  2. //返回前端Post提交的数据
  3. print_r($_POST);

最终输出结果:前端页面上有个按钮”ajax-post-cors”,点击后页面提示:Array ( [email] => admin@php.cn [password] => 123456 )
表示跨域访问成功。

2 json

json是一种语法,用来序列化其它语言创建的数据类型
json独立于任何编程语言,几乎所有编程语言都提供了访问json数据的API接口
仅支持6种数据类型:对象、数组、数值、字符串、布尔值、null
json只是借用了JS中的一些数据表示语法,与js并无关系
注:json不支持undefined。因为除了js外,其他语言没有这个词

  1. //json提供了两个方法:
  2. //json.stringigy(data,replacer,space) :将JS对象,序列化为json字符串,下面代码会分别介绍三个参数的作用
  3. //json.parse():将json字符串,解析为js对象
  4. console.log(JSON.stringify(3.14),typeof JSON.stringify(3.14)); //输出3.14 string
  5. console.log(JSON.stringify("php.cn"),typeof JSON.stringify("php.cn")); //输出"php.cn" string
  6. console.log(JSON.stringify(true),typeof JSON.stringify(true)); //输出true string
  7. console.log(JSON.stringify(null),typeof JSON.stringify(null)); //输出null string
  8. console.log(JSON.stringify([1,2,3]),typeof JSON.stringify([1,2,3])); //输出[1,2,3] string
  9. console.log(JSON.stringify({x:"a",y:"b"}),typeof JSON.stringify({x:"a",y:"b"})); //输出{"x":"a","y":"b"} string
  10. //json其实不是数据类型,只是一个具有特殊格式的字符串而已
  11. //对json格式字符串的特殊操作,主要通过后面二个参数
  12. //第二个参数支持数组 和 函数
  13. //数组
  14. console.log(JSON.stringify({x:"a",y:"b",z:"c"})); //输出{"x":"a","y":"b","z":"c"}
  15. console.log(JSON.stringify({x:"a",y:"b",z:"c"},[x,y])); //输出{"x":"a","y":"b"}
  16. //函数
  17. console.log(JSON.stringify({a:1,b:2,c:3},(k,v) =>{
  18. //将需要过滤的数据直接返回undefined
  19. if(v<2) return undefined;
  20. //过滤掉值小于2的数据,即a:1,过滤之后,返回其它 >=2 的数据
  21. return v;
  22. }));
  23. //第三个参数,用来格式化输出json字符串
  24. console.log(JSON.stringify({a:1,b:2,c:3},null,2));//前面输出两个空格
  25. //输出:
  26. //{
  27. // "a":1,
  28. // "b":2,
  29. // "c":3
  30. //}

3 常用数组函数

  1. let arr = [1,2,3];
  2. //1 类似栈的方法
  3. arr.push(4,5);//进栈,返回5,修改后的数组长度
  4. arr.pop();//出栈,返回5,数组中索引最大的值,即最后进入数组的值
  5. //2 类似队列的方法
  6. arr.shift();//出队,返回1,即数组中第一项
  7. arr.unshift(45);//入队,返回修改后的数组长度
  8. // shift结合push,unshift结合pop可以实现像队列一样操作数组
  9. //3 join():与字符串split()相反,将数组转化为字符串返回
  10. let arr =["电脑","手机","相册"];
  11. console.log(arr.join());//返回:电脑,手机,相册
  12. console.log(arr.join("*"));//返回
  13. //4 concat()数组合并
  14. console.log([1,2,3].concat([4,5],[6,7 ]));//输出:[1,2,3,4,5,6,7]
  15. console.log([1,2,3].concat(123,["php",true],{x:1,y:2 }));//输出:[1,2,3,123,"php",true,{x:1,y:2}]
  16. //5 slice():返回数组中的成员
  17. arr = [1,2,3,4,5];
  18. let res = arr.slice(2,4);//返回 [3,4],即索引为2和3的值,如果只写一个,就直接取到原来数组末位。
  19. //6 splice(开始索引,删除的数量,插入的数据):数组的增删改操作,本质工作是删除数组元素,返回被删除的元素
  20. arr = [1,2,3,4,5];
  21. console.log(arr.splice(2));//如果只有一个参数,即是删除索引从2开始,后面所有的元素,返回值[3,4,5],此时arr:[1,2]
  22. arr = [1,2,3,4,5];
  23. console.log(arr.splice(2,2));//如果有两个参数,即是说明了删除的数量,返回[3,4],此时arr:[1,2,5]
  24. arr = [1,2,3,4,5];
  25. console.log(arr.splice(2,28899));//三个或者三个以上,返回值依然是删除的元素[3,4],但插入了新的元素,arr:[1,2,88,99,5],
  26. //以上语句也可以写成 console.log(arr.splice(2,2,...[88,99])); 不能没有...
  27. //7 排序
  28. arr = ["a","c","b"];
  29. console.log(arr.sort());//按照字母的排列顺序,输出["a","b","c"]
  30. //如果数组元素是数字,排列是先转成字符串,然后按照左侧开始每一位的数字的顺序
  31. arr = [10,9,22,4];
  32. console.log(arr.sort());//输出:[10,22,4,9],因为左侧开始的第一位分别是1,2,4,9
  33. arr.sort((a,b) => a-b);//升序排列,如果后面改成b-a,就是降序排列
  34. console.log(arr);//此时arr就是按照升序排列
  35. //8 遍历map
  36. arr = [1,2,3,4,5];
  37. console.log(arr.foreach(item => console.log(item))); //逐行输出1,2,3,4,5,该没有返回值,如果我们需要赋值给某个变量,就不太方便
  38. let res = arr.map(item => item); //此时res就是遍历arr数组后得到的数组,由于map里面是item => item,所以res 和arr是两个一模一样的数组,但如果item => item*2,则res里面每个元素都是arr对应元素的两倍
  39. //9 过滤filter()
  40. arr = [1,2,3,4,5];
  41. console.log(arr.filter(item => item % 2));//item%2 为真,即item%2不为0,即是奇数
  42. //10 归内reduce(callback(prev,curr),base)
  43. arr = [1,2,3,4,5];
  44. console.log(arr.reduce((prev,curr) => {
  45. //逐行输出:1 2
  46. // 3 3
  47. // 6 4
  48. // 10 5
  49. console.log(prev,curr);
  50. return prev+curr;
  51. }); //最终输出 15 (数组求和)
  52. console.log(arr.reduce((prev,curr) => {
  53. return prev*curr;
  54. },2)); //最终返回值240,计算过程是:基础值2*1*2*3*4*5
声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议