對於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):'' }