Blogger Information
Blog 47
fans 3
comment 0
visits 38277
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
数组函数、JSON、get,post发起ajx请求、cors,jsonp跨域原理
Original
764 people have browsed it

1. 自选10个数组函数练习

  1. <script>
  2. // 1.栈方法
  3. // 栈:后进先出
  4. // 队:先进先出
  5. let arr = [];
  6. let res;
  7. // 1. push();pop():在数组的尾部增删
  8. res = arr.push(1, 2, 3);
  9. console.log(arr.pop());
  10. console.log(arr.pop());
  11. console.log(arr.pop());
  12. console.log("%c----", "color:red");
  13. // 2. unshift(),shift():在数组的头部进行增删
  14. // console.log(arr.unshift(4, 5, 6));
  15. res = arr.unshift(4, 5, 6);
  16. console.log(arr.shift());
  17. console.log(arr.shift());
  18. console.log(arr.shift());
  19. console.log("%c----", "color:red");
  20. // 3. push()+shift():模拟队列,尾部进入,头部出去
  21. res = arr.push(1, 2, 3);
  22. console.log(arr.shift());
  23. console.log(arr.shift());
  24. console.log(arr.shift());
  25. console.log("%c----", "color:red");
  26. // 4. pop()+unshift():模拟队列,头部进入,尾部出去
  27. res = arr.unshift(1, 2, 3);
  28. console.log(arr.pop());
  29. console.log(arr.pop());
  30. console.log(arr.pop());
  31. console.log("%c----", "color:red");
  32. // 5. join():将数组转为字符串返回
  33. arr = ["电脑", "手机", "相机"];
  34. res = arr.join("---");
  35. console.log(res);
  36. console.log("%c----", "color:red");
  37. // 6. concat()数组合并
  38. console.log([1, 2, 3].concat([4, 5, 6], [7, 8, 9]));
  39. console.log("%c----", "color:red");
  40. // 7.slice():返回数组中的部分成员
  41. arr = [1, 2, 3, 4, 5];
  42. // 取最后二个数字
  43. console.log(arr.slice(3));
  44. console.log("%c----", "color:red");
  45. // 8. splice (开始索引,删除数据,插入数据...) :数组的增删改
  46. arr = [1, 2, 3, 4, 5, 6];
  47. // 删除
  48. res = arr.splice(2);
  49. console.log(arr);
  50. // 更新
  51. arr = [1, 2, 3, 4, 5, 6];
  52. res = arr.splice(1, 2, ...[88, 99]);
  53. console.log(arr);
  54. // 新增:将第二个参数设置为0
  55. arr = [1, 2, 3, 4, 5];
  56. res = arr.splice(1, 0, ...[88, 99]);
  57. console.log(arr);
  58. console.log("%c----", "color:red");
  59. // 9. sort()排序:默认是字母表顺序
  60. arr = ["p", "b", "a"];
  61. console.log(arr);
  62. arr.sort();
  63. console.log(arr);
  64. console.log("%c----", "color:red");
  65. // 10. map遍历:有返回值
  66. arr = [1, 2, 3, 4, 5, 6];
  67. res = arr.map((item) => item);
  68. console.log(res);
  69. console.log("%c----", "color:red");
  70. // 11. filter() 过滤
  71. arr = [1, 2, 3, 4, 5];
  72. res = arr.filter((item) => !(item % 2));
  73. console.log(res);
  74. console.log("%c----", "color:red");
  75. // 12. redice(callback(prev,curr)):归并
  76. arr = [1, 2, 3, 4, 5];
  77. res = arr.reduce((prev, curr) => {
  78. return prev + curr;
  79. });
  80. console.log(res);
  81. </script>

2.JSON 二个函数及参数功能

  • JSON.stringify():将 js 数据序列化为 json 字符串

  1. <script>
  2. // Array,objecy
  3. console.log(JSON.stringify([1, 2, 3]));
  4. console.log(JSON.stringify({ a: 3, b: 2, c: 3 }));
  5. // 函数
  6. console.log(
  7. JSON.stringify({ a: 1, b: 2, c: 3 }, (k, v) => {
  8. // 将需要过滤掉的数据直接返回undefined
  9. if (v < 2) return undefined;
  10. return v;
  11. })
  12. );
  13. // 格式化输出json字符串
  14. console.log(JSON.stringify({ a: 1, b: 2, c: 3 }, null, "---"));
  15. console.log(obj);
  16. </script>
  • JSON.parse(): 解析 json 字符串为 js 对象

  1. <script>
  2. let obj = JSON.parse(`{"a":1,"b":2,"c":3}`);
  3. console.log(obj.a, obj.b, obj.c);
  4. // 第二个参数可以对json的数据进行处理后再返回
  5. obj = JSON.parse(`{"a":1,"b":2,"c":3}`, (k, v) => {
  6. if (k === "") return v;
  7. return v * 2;
  8. });
  9. console.log(obj);
  10. </script>

3. get、post 发起 ajax 请求

  • ajax-get 请求

  1. <button>ajax-get请求</button>
  2. <p></p>
  3. <script>
  4. const btn = document.querySelector("button");
  5. btn.onclick = () => {
  6. const xhr = new XMLHttpRequest();
  7. xhr.responseType = "json";
  8. xhr.open("get", "test1.php?id=2");
  9. xhr.onload = () => {
  10. console.log(xhr.response);
  11. let user = `姓名:${xhr.response.name},邮箱:${xhr.response.email}`;
  12. document.querySelector("p").innerHTML = user;
  13. };
  14. xhr.onerror = () => console.log("error");
  15. xhr.send(null);
  16. };
  17. </script>

ajax-get 请求 PHP 代码

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

  1. <html lang="en">
  2. <head>
  3. <meta charset="UTF-8" />
  4. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  5. <title>ajax-post请求</title>
  6. </head>
  7. <style>
  8. .login {
  9. width: 20em;
  10. border: 1px solid;
  11. padding: 0 1em 1em;
  12. background-color: lightcyan;
  13. margin: 2em auto;
  14. display: grid;
  15. place-items: center;
  16. }
  17. .login form {
  18. display: grid;
  19. grid-template-columns: 3em 1fr;
  20. gap: 1em 0;
  21. }
  22. /* 按钮与提示信息显示在第二列 */
  23. .login form button,
  24. .tips {
  25. grid-area: auto / 2;
  26. }
  27. </style>
  28. <body>
  29. <div class="login">
  30. <form action="" method="POST">
  31. <label for="email">邮箱:</label>
  32. <input type="email" name="email" id="email" />
  33. <label for="password">密码:</label>
  34. <input type="password" name="password" id="password" />
  35. <button>提交</button>
  36. <span class="tips"></span>
  37. </form>
  38. </div>
  39. <script>
  40. const form = document.querySelector(".login form");
  41. const btn = document.querySelector(".login button");
  42. const tips = document.querySelector(".tips");
  43. btn.onclick = (ev) => {
  44. ev.preventDefault();
  45. const xhr = new XMLHttpRequest();
  46. xhr.open("post", "test2.php");
  47. xhr.onload = () => (tips.innerHTML = xhr.response);
  48. xhr.send(new FormData(form));
  49. };
  50. </script>
  51. </body>
  52. </html>

ajax-post 请求 PHP 代码:

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

4. 理解并写出 cors、jsonp 跨域的源码

cors 跨域:不同源的请求,跨协议|域名|端口的请求,需服务器端请求的文件开启跨域许可。

jsonp 跨域:跨域标签实现,link 的 href,img 的 src,script 的 src,a 标签的 href 等来实现
jsonp 跨域:可以不需要服务器端请求的文件开启跨域许可
jsonp 跨域:前端一个调用函数,把函数名告诉服务器端,服务器端把 json 格式数据填充前端告诉它的函数名,进行动态输出

  • 4.1 cors 跨域
cors-get 跨域

  1. <button>ajax-get-cors</button>
  2. <p></p>
  3. <script>
  4. const btn = document.querySelector("button");
  5. btn.onclick = (ev) => {
  6. const xhr = new XMLHttpRequest();
  7. xhr.open("get", "http://world.io/cors1.php");
  8. xhr.onload = () => (document.querySelector("p").innerHTML = xhr.response);
  9. xhr.send(null);
  10. };
  11. </script>
cors-get 跨域 PHP 代码
  1. <?php
  2. // 在服务器端开启跨域许可
  3. // header ('Access-Control-Allow-Origin: http://hello.io');
  4. header ('Access-Control-Allow-Origin: *');
  5. // *:任何来源
  6. echo 'CORS:跨域请求成功';
cors-post 跨域

  1. <button>ajax-post-cors</button>
  2. <p class="tips"></p>
  3. <script>
  4. const btn = document.querySelector("button");
  5. const tips = document.querySelector(".tips");
  6. btn.onclick = (ev) => {
  7. const xhr = new XMLHttpRequest();
  8. xhr.open("post", "http://world.io/cors2.php");
  9. xhr.onload = () => (tips.innerHTML = xhr.response);
  10. let formData = new FormData();
  11. formData.append("email", "admin@php.cn");
  12. formData.append("password", "123456");
  13. xhr.send(formData);
  14. };
  15. </script>
cors-get 跨域 PHP 代码
  1. <?php
  2. header ('Access-Control-Allow-Origin: *');
  3. // 返回前端post提交的数据
  4. print_r($_POST);

4.2 jsonp 跨域

  1. <button>jsonpadding-cors</button>
  2. <p></p>
  3. <script>
  4. function getUser(data) {
  5. console.log(data);
  6. let user = data.name + ":" + data.email;
  7. document.querySelector("p").innerHTML = user;
  8. }
  9. const btn = document.querySelector("button");
  10. btn.onclick = () => {
  11. let script = document.createElement("script");
  12. script.src = "http://world.io/cors3.php?callback=getUser";
  13. document.body.insertBefore(script, document.body.firstElementChild);
  14. };
  15. </script>
  • jsonp 跨域 PHP 代码:
  1. <?php
  2. // jsonp 不需要授权给前端
  3. // 只要返回一个使用json做为参数的函数调用语句就可以了
  4. // 将前端需要的数据以json格式放到这个函数的参数中就行了
  5. // 必须要知道前端js要调用的函数名称
  6. $callback = $_GET['callback'];
  7. // 服务器中需要返回的数量
  8. $data = '{ "name": "天蓬", "email": "tp@php.cn" }';
  9. $data = '{ "name": "灭绝", "email": "mj@php.cn" }';
  10. // 在后端生成一条js函数调用语句:getuser({ name: "天蓬老师", email: "tp@php.cn" });
  11. 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