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 });
     
  • 相关阅读:
    12个非常不错的javascript类库
    CSS中单位em和rem的区别
    CSS中box-sizing属性的作用
    网页设计中的默认字体样式详解
    jQuery遍历Table表格的行和列
    css常用解决方案
    JS判断字符串小括号是否成对合法
    Less编码规范
    React九宫格抽奖
    n个有序数组,取出k个最大值
  • 原文地址:https://www.cnblogs.com/scottjeremy/p/5814141.html
Copyright © 2011-2022 走看看