Use jsonp to obtain data across domains.
js part
(function(window, document) { 'use strict'; var jsonp = function(url, data, callback) { //1、挂载回调函数 var fnsuffix = Math.random().toString().replace('.', ''); var cbFuncName = 'my_json_cb' + fnsuffix; window[cbFuncName] = callback; //2、将data转换成url字符串的形式 //{id=1,count=4}==>id=1&count=4 var querystring = url.indexOf('?') == -1 ? '?' : '&'; //判断url中最后是否有?,没有则为? for (var key in data) { querystring += key + '=' + data[key] + '&'; } //3、处理url中回调函数 url+=callback=sdgade querystring += 'callback=' + cbFuncName; //querystring=?id=1&count=4&callback=sdgade //4、创建一个script标签 var scriptElement = document.createElement('script'); scriptElement.src = url + querystring; //5、把script标签放到页面上 document.body.appendChild(scriptElement); }; window.$jsonp = jsonp; })(window, document)
Test
<!DOCTYPE html> <html> <head> <title>jsonp</title> </head> <body> <div id="htt"></div> <script type="text/javascript" src="http.js"></script> <script> (function(){ $jsonp('http://api.douban.com/v2/movie/in_theaters',{}, function(data){ document.getElementById('htt').innerHTML=JSON.stringify(data); }); })() </script> </body> </html>
in the page and the result can be returned. The page displays as, indicating that the acquisition is successful!
For more articles related to JSONP implementation, please pay attention to the PHP Chinese website!