实现跨域请求的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 });
 
posted @ 2016-08-28 00:04  Scott-Jeremy  阅读(594)  评论(0编辑  收藏  举报