Jsonp跨域
Jsonp.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Jsonp Request</title> <script type="text/javascript" src="js/jquery-1.7.1.min.js"></script> </head> <body> <script> function jsonp(url,data,callback){ //跨域数据请求 var script = document.createElement('script'); document.body.appendChild(script); data = data || {}; data.callback = 'cb' + new Date().getTime(); window[data.callback] = callback; window["cbName"] = data.callback; url += '?' + $.param(data); script.src = url; script.onload = function(){ document.body.removeChild(script); } } jsonp('http://c.cros.com/jsonpS.js',{test:'123'},function(data){ console.log(data); }) </script> </body> </html>
JsonpS.js
var jsonData = {a:1,b:2}; function obj2string(o) { var r = []; if (typeof o == "string") { return "\"" + o.replace(/([\'\"\\])/g, "\\$1").replace(/(\n)/g, "\\n").replace(/(\r)/g, "\\r").replace(/(\t)/g, "\\t") + "\""; } if (typeof o == "object") { if (!o.sort) { for (var i in o) { r.push(i + ":" + obj2string(o[i])); } if ( !! document.all && !/^\n?function\s*toString\(\)\s*\{\n?\s*\[native code\]\n?\s*\}\n?\s*$/.test(o.toString)) { r.push("toString:" + o.toString.toString()); } r = "{" + r.join() + "}"; } else { for (var i = 0; i < o.length; i++) { r.push(obj2string(o[i])) } r = "[" + r.join() + "]"; } return r; } return o.toString(); } jsonData = obj2string(jsonData); eval(cbName + '(' + jsonData + ')');
另:CORS跨域请求 http://blog.csdn.net/fdipzone/article/details/46390573/