• 数据交互 jsonp插件


    对于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):''
    }
  • 相关阅读:
    CSS display:none和visibility:hidden区别
    Eclipse 开发版本选择
    JavaScript 三种弹出框
    jstree的数据后台生成
    C# Enum,Int,String的互相转换 枚举转换
    JS 异常: Uncaught RangeError: Maximum call stack size exceeded
    JS中encodeURI,escape,encodeURIComponent区别
    安卓Android手机系统内文件夹目录解释
    jquery操作select(取值,设置选中)
    单例/单体模式(Singleton)
  • 原文地址:https://www.cnblogs.com/zhouxiaohouer/p/8031733.html
Copyright © 2020-2023  润新知