zoukankan      html  css  js  c++  java
  • 数据交互 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):''
    }
  • 相关阅读:
    筛选法求素数
    正整数N是否是素数
    前N个自然数的随机置换
    【数据结构与算法分析——C语言描述】第二章总结 算法分析
    【数据结构与算法分析——C语言描述】第一章总结 引论
    递归打印头文件
    选择符
    选择器
    认识CSS样式
    表单-续
  • 原文地址:https://www.cnblogs.com/zhouxiaohouer/p/8031733.html
Copyright © 2011-2022 走看看