jquery&javascript 跨域jsonp
$(function(){ $.ajax({ type: "get", async: false, url: "http://flightQuery.com/jsonp/flightResult.aspx?code=CA1998", dataType: "jsonp", jsonp: "callback",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(一般默认为:callback) jsonpCallback:"flightHandler",//自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名,也可以写"?",jQuery会自动为你处理数据 success: function(json){ alert('您查询到航班信息:票价: ' + json.price + ' 元,余票: ' + json.tickets + ' 张。'); }, error: function(){ alert('fail'); } }); });
另外推荐一款jsonp跨域独立插件:http://www.uedsc.com/flyjsonp.html
源码:https://github.com/alotaiba/FlyJSONP
原生跨域封装:
function jsonp(setting) { setting.data = setting.data || {}; setting.key = setting.key || "callback"; setting.callback = setting.callback || function() {}; setting.data[setting.key] = "__onGetData__"; window.__onGetData__ = function(data) { setting.callback(data); }; var script = document.createElement("script"); var query = []; for (var key in setting.data) { query.push(key + "=" + encodeURIComponent(setting.data[key])); } script.type="" script.src = setting.url + "?" + query.join("&"); document.head.appendChild(script); document.head.removeChild(script); } jsonp({ url:w, key:'jsoncallback', callback:function(d){ console.log(d) } })
http://websong.gitee.io/songyublog/