zoukankan      html  css  js  c++  java
  • 实现跨域请求的4种方法

    模拟服务器端的PHP文件:

    service:

    1 <?php
    2 //允许访问
    3 header('Access-Control-Allow-Origin:*');
    4 @$callback=$_GET['callback'];
    5 //创建数据
    6 $userInfo = array('id'=>1,'username'=>'Scott Jeremy','email'=>'673457942@qq.com');
    7 //编译成JSON
    8 $result = json_encode($userInfo);
    9 echo $callback."({$result})";

    service2:

    1 <?php
    2 header('Access-Control-Allow-Origin:*');
    3 $userInfo = array('id'=>1,'username'=>'Scott Jeremy','email'=>'673457942@qq.com');
    4 echo json_encode($userInfo);

    原生Javascript:

     1 function jsonpCallback(result) {
     2     //alert(result);会返回jsonpCallback({"id":1,"username":"Scott Jeremy","email":"673457942@qq.com"})
     3     alert('My :'+result.username+'.'+'My email:'+result.email);
     4 }
     5 //创建script标签
     6 var script = document.createElement('script');
     7 //定义script标签的url
     8 script.src = 'http://localhost/service.php?callback=jsonpCallback';
     9 //把标签放到head中
    10 document.getElementsByTagName('head')[0].appendChild(script);

    利用jQuery实现跨域请求有三种方法:

    1:AJAX请求
     1 $('#btn1').on('click',function () {
     2     $.ajax({
     3     //设置url
     4         url:'http://localhost/service2.php',
     5     //用什么方式请求
     6         type:'GET',
     7     //返回来用什么形式解析
     8         dataType:'json',
     9         success:function (data) {
    10             alert(data.username);
    11             alert(data.email);
    12         },
    13         error:function () {
    14             alert('error');
    15         }
    16     });
    17 });

    2:JSONP实现跨域请求
     1 $('#btn2').on('click',function () {
     2     $.ajax({
     3         url:'http://localhost/service.php',
     4         type:'GET',
     5         dataType:'JSONP',
     6     //JSONP回调函数名
     7         jsonp:'callback',
     8     //JSONP回调后的JSON名,相当于JSON文章中的book
     9         jsonpCallback:'Jeremy',
    10         success:function (data) {
    11             alert(data.username);
    12             alert(data.email);
    13         }
    14     })
    15 });
    3:getJSON(最简单的一种:缩写)
    1 $('#btn3').on('click',function () {
    2     $.getJSON('http://localhost/service.php?callback=?',function (data) {
    3         alert(data.username);
    4         alert(data.email);
    5     })
    6 });
     
  • 相关阅读:
    HTML5 Video/Audio播放本地文件
    jquery 美化弹出提示 漂亮的Dialog 对话框
    JavaScript中变量、作用域、内存问题
    利用nethogs查看哪些进程占用网络带宽
    Dell服务器硬件监控,使用omreport出现object not found 错误解决
    filebeat收集nginx的json格式日志
    利用logrotate切割nginx的access.log日志
    Linux下单机部署ELK日志收集、分析环境
    linux开启Rsyslog服务收集日志
    mysql占用磁盘IO过高的解决办法
  • 原文地址:https://www.cnblogs.com/scottjeremy/p/5814141.html
Copyright © 2011-2022 走看看