jsonp源码解析

源码github地址https://github.com/webmodules/jsonp/blob/master/index.js

var debug = require('debug')('jsonp');
//node.js的debug模块,可以在控制台打印错误消息

一般我们在测试的时候都是直接console.log()来打印消息的,但是在线上生产环境用console.log的话,每次都要将它删除,非常麻烦,而debug模块在线上生产环境是不会打印的。

module.exports = jsonp;
//导出jsonp模块,供其他模块使用。
function jsonp(url, opts, fn){}
/*主要的函数,它有三个参数
  url 请求地址的url
  opts {
    param 与后端约定请求的字段名称,默认是callback 
    prefix  指定回调函数params的回调句柄前缀,默认为__jp
    name 指定回调函数的句柄 默认是__jp+数字
    timeout 设定一个响应时间,默认为60000ms,如果在设定设计内没有响应,则会提交error
}
  fn 请求事件的回调函数,负责接受data响应数据和请求失败的err信息
*/

 
 if ('function' == typeof opts) {
    fn = opts;
    opts = {};
  }
//如果opts的类型是function,则把opts赋给fn,然后opts设为空对象
  if (!opts) opts = {};
//如果opts不存在,则设置opts为空对象
var prefix = opts.prefix || '__jp';
//opts对象的prefix属性默认为__jp
var id = opts.name || (prefix + (count++));
//使用提供的回调名称。
//否则通过递增计数器来生成唯一的名称。
var param = opts.param || 'callback';
//param默认为callback
var timeout = null != opts.timeout ? opts.timeout : 60000;
//timeout默认为60000ms
var enc = encodeURIComponent;
var target = document.getElementsByTagName('script')[0] || document.head;
//获取第一个script标签或者head标签
var script;
//后面创建script标签要用
var timer;
 if (timeout) {
    timer = setTimeout(function(){
      cleanup();
      if (fn) fn(new Error('Timeout'));
    }, timeout);
  }

  function cleanup(){
    if (script.parentNode) script.parentNode.removeChild(script);
    window[id] = noop;
    if (timer) clearTimeout(timer);
  }

/*超时设置,如果响应超时,则原先添加的script标签,置window[id]为空对象,清楚timer计时器,抛出错误

  function cancel(){
    if (window[id]) {
      cleanup();
    }
  }

//取消对jsonp模块的使用
//服务器端解析params.param进行调用函数
  window[id] = function(data){
    debug('jsonp got', data);
    // 恢复初始值
    cleanup();
    //返回数据
    if (fn) fn(null, data);
  };
url += (~url.indexOf('?') ? '&' : '?') + param + '=' + enc(id);
url = url.replace('?&', '?');

/*对字符串url进行字符串检测,同时如果有param参数,则拼接在后面
举个例子:http://freegeoip.net/json/?callback=handleResponse 
整一个字符串是url,检测是否有?,然后后面接callback=handleResponse


 script = document.createElement('script');
 script.src = url;
 target.parentNode.insertBefore(script, target);

//创建script标签,设置它的src属性为url,插入到第一个script标签前或者head里面

本文参考https://blog.csdn.net/Mr_YanYan/article/details/78534246,在这个博客的基础上加上自己的看法,从而加深对jsonp的理解和使用,如有错误,请告知

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值