博客列表 >JavaScript:CORS跨域请求/动态生成标签

JavaScript:CORS跨域请求/动态生成标签

阿心
阿心原创
2020年05月26日 13:54:58925浏览

cors跨域请求

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>cors跨域请求</title>
  6. </head>
  7. <body>
  8. <button>CORS跨域请求按钮</button>
  9. <h2></h2>
  10. <script>
  11. //获取按钮
  12. var btn = document.querySelector("button");
  13. //获取点击事件
  14. btn.addEventListener("click",function(){
  15. var xhr = new XMLHttpRequest();
  16. xhr.onreadystatechange=function(){
  17. if(xhr.readyState === 4 && xhr.status === 200)
  18. {
  19. console.log(xhr.responseText);
  20. //页面渲染
  21. var h2 = document.querySelector("h2");
  22. h2.innerHTML = xhr.response;
  23. }
  24. };
  25. xhr.open("GET","http://127.0.0.7/0522/test1.php",true);
  26. xhr.send(null);
  27. },false);
  28. </script>
  29. </body>
  30. </html>

PHP设置请求头

  1. <?php
  2. //如果是ip,后免不需要加“/” 。
  3. header('Access-Control-Allow-Origin:http://127.0.0.8');
  4. //header('Access-Control-Allow-Origin:*');
  5. echo "跨域CORS请求1111";

动态按钮生成CORS跨域请求

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>CORS--跨域请求获取函数数据</title>
  6. </head>
  7. <body>
  8. <!--动态生成请求-->
  9. <button>动态按钮生成CORS跨域请求</button>
  10. <script>
  11. function handle(jsondata){
  12. console.log(jsondata);
  13. var data = JSON.parse(jsondata);
  14. console.log(data);
  15. var ul = document.createElement("ul");
  16. ul.innerHTML += "<li>" + data.title + "</li>";
  17. ul.innerHTML += "<li>" + data.user.account + "</li>";
  18. ul.innerHTML += "<li>" + data.user.user + "</li>";
  19. document.body.appendChild(ul);
  20. }
  21. var btn = document.querySelector("button");//获取按钮
  22. //添加事件
  23. btn.addEventListener('click',function(){
  24. // 生成script标签
  25. var script=document.createElement("script");
  26. script.src="http://127.0.0.7/0522/test2.php?json=handle&id=2";
  27. document.head.appendChild(script);
  28. },false);
  29. </script>
  30. <!-- //函数在前,请求在后 固定写上-->
  31. <!-- <script src="http://127.0.0.7/0522/test2.php?json=handle"></script>-->
  32. </body>
  33. </html>

被请求的PHP处理文件

  1. <?php
  2. $callback = $_GET['json'];
  3. //echo $data;
  4. $id=$_GET['id'];
  5. $users = [
  6. '{"account":"admin","user":"管理员"}',
  7. '{"account":"super","user":"超级管理员"}',
  8. ];
  9. //array_key_exists — 检查数组里是否有指定的键名或索引
  10. if(array_key_exists(($id-1),$users)){
  11. $user = $users[$id-1];
  12. }
  13. $json = '{
  14. "title":"用户信息",
  15. "user":'.$user.'
  16. }';
  17. echo $callback .'('. json_encode($json).')';

总结:写到怕,每次抄写的时候感觉大概思路已经通了。自己写的时候就思路非常乱,不知道怎么写,也不知道该写什么或者他的思路应该是怎么样顺序去写的

声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议