jsonp跨域请求具体写法(原生,jquery,angular自定义服务)

来源:互联网 发布:易语言数据库排序 编辑:程序博客网 时间:2024/06/04 19:09
<!DOCTYPE html><html><head lang="en">    <meta charset="UTF-8">    <title></title>    <script src="../app/bower_components/angular/angular.js"></script>    <script src="../app/bower_components/jquery/dist/jquery.js"></script></head><body ng-app='app'><div ng-controller="demoController"></div>    <script>        //原生js写法       /* (function (){            var script = document.createElement('script');            script.src = "http://api.douban.com//v2/movie/in_theaters?count=2&start=4&callback=func";            document.body.append(script);        })();        function func(data){           console.log(data.subjects);        }*/        //jquery写法       /* (function (){            $.ajax({                type: "get",                async: false,                url: "http://api.douban.com//v2/movie/in_theaters?count=2&start=4",                dataType: "jsonp",                jsonp: "callback",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(默认为:callback)                jsonpCallback: "func",//自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名                success: function (data) {                    console.log(data.subjects);                },                error: function () {                   console.log('有错');                }            });        })();*/        //angualr解决跨域请求        /*        * 使用服务$http.jsonp,但是此时豆瓣接口并不接受自定义回调函数名称,协议不了,所以需要改进,angular必须使用JSON-CALLBACK的形式,返回后会自动生成函数名称        * */        var app = angular.module('app',[]);        app.controller('demoController',['$scope','$http',function ($scope,$http){           /* $http.jsonp('http://api.douban.com/v2/movie/in_theaters?callback=JSON_CALLBACK&count=2&start=4').then(function (res){                console.log(res);            })*/            $http.jsonp('./angular_callback_0.json?callback=JSON_CALLBACK').then(function (res){                console.log(res);            })        }])    </script></body></html>

angular自定义服务,解决跨域请求

(function (angular){    var http = angular.module('moviecat.services.http',[]);    http.service('HttpService',['$document','$window',function ($document,$window){        this.jsonp = function (url,data,callback){            //解析字符串            var queryString = url.indexOf('?') == -1 ? '?' : '&';            for(var key in data){                queryString += key + "=" + data[key] + '&';            };            //绑定回调函数            var cbname = 'jsonp_'+Math.random().toString().replace('.','');            $window[cbname] = function (data){                callback(data)                //防止页面上出现过多的script脚本,所有每次调用后,即时删除                ;$document[0].body.removeChild(script);            };            queryString += 'callback='+cbname;            var script = $document[0].createElement('script');            script.src = url + queryString;            //添加到页面中            $document[0].body.append(script);        }    }])})(angular);
原创粉丝点击