數據交互 jsonp插件

對於jsonp跨域問題能夠戳:http://www.cnblogs.com/zhouxiaohouer/p/7900602.htmlhtml

另外在github上還有一個jsonp的插件,簡單易用,不引入jQuery也能夠輕易使用。git

插件地址:https://github.com/webmodules/jsonpes6

安裝:github

npm install jsonp

使用:web

    // 格式:
    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能夠更好地封裝jsonpnpm

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):''
}
相關文章
相關標籤/搜索