jsonp示例,使用js获取本地访问公网的IP

技术 置顶 精帖
0 889
peng49
peng49 2021-11-25 18:07:43
 

前端代码 jsonp.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>jsonp demo</title>
  6. </head>
  7. <body>
  8. <div id="callback">
  9. </div>
  10. <div id="ipCallback"></div>
  11. <div id="server-info"></div>
  12. </body>
  13. <script>
  14. function callback(obj) {
  15. document.getElementById('callback').innerText = '国外Ip:' + obj.ip;
  16. console.log('国外Ip:' + obj.ip)
  17. }
  18. function ipCallback(obj) {
  19. document.getElementById('ipCallback').innerText = '国内Ip:' + obj.ip;
  20. console.log('国内Ip:' + obj.ip)
  21. }
  22. function parseServer(server) {
  23. document.getElementById('server-info').innerText = JSON.stringify(server)
  24. console.log(server)
  25. }
  26. </script>
  27. <!--回调方法:callback-->
  28. <script src="https://api.ipify.org/?format=jsonp"></script>
  29. <!--回调方法:ipCallback-->
  30. <script src="https://www.taobao.com/help/getip.php"></script>
  31. <!--回调方法:parseServer-->
  32. <script src="http://localhost/jsonp.php?callback=parseServer"></script>
  33. </html>

后端代码

  1. <?php
  2. $callback = $_GET['callback'] ?? "callback";
  3. echo "{$callback}(" . json_encode(['SERVER' => $_SERVER]) . ")";

页面显示效果

回帖
登录
忘记密码?