对于jsonp跨域问题可以戳:http://www.cnblogs.com/zhouxiaohouer/p/7900602.html
另外在github上还有一个jsonp的插件,简单易用,不引入jQuery也可以轻易使用。
插件地址:https://github.com/webmodules/jsonp
安装:
npm install jsonp
使用:
// 格式: jsonp(url, opts, (err,data)=>{to-do}) // 参数说明: // 数据地址: url (String) url to fetch // 配置选项对象 opts (Object), optional // 重要:和后端约定的函数名 param (String) name of the query string parameter to specify the callback (defaults to callback) // 熟悉:超时时间 timeout (Number) how long after a timeout error is emitted. 0 to disable (defaults to 60000) prefix (String) prefix for the global callback functions that handle jsonp responses (defaults to __jp) name (String) name of the global callback functions that handle jsonp responses (defaults to prefix + incremented counter) // 回调函数 (err,data)=>{to-do}
利用es6中的promise可以更好地封装jsonp
import jsonp from 'jsonp' export default function iJSONP(url,queryData,option) { // 有问号就会有查询字符串,直接在后面加&和转化后的字符串 // 没有问号直接在后面加?和转化后的字符串 url = (url.indexof('?')<0?'?':'&')+data2urlstring(queryData) return new Prommise((resolve,reject)=>{ jsonp(url,option,(err,data)=>{ err?reject(err):resolve(data) }) }) } function data2urlstring(data) { let str = '' for(var key in data){ let value = data[key]?data[key]:'' str += `&${key}=${value}` } // 去掉第一个& return url?url.substring(1):'' }