源码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里面