All files / io iframePost.js

97.67% Statements 84/86
63.83% Branches 30/47
100% Functions 9/9
97.67% Lines 84/86

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209                                                                1x       9x 9x   9x     9x       3x 3x 1x 1x   3x       2x 2x 2x 2x       1x 1x 1x 1x 1x   1x       1x 1x             1x 1x 1x       2x 2x                             2x 2x   2x 2x 2x       2x 2x 2x   2x 2x 1x 2x     2x           2x   1x 1x 2x           2x     2x   2x 2x   2x 2x   2x 2x   2x 1x 1x     2x 2x 2x 1x 1x 1x     1x 1x   2x 2x 2x   2x 2x   2x 1x 1x 1x 1x             2x 2x 2x 2x   2x 2x     2x     2x         2x   2x     1x  
/**
 * 封装 iframe post 模式
 * - requires jQuery/Zepto
 * @method io/iframePost
 * @param {Object} spec 请求选项
 * @param {Object} [spec.form=null] 要请求的表单
 * @param {String} spec.url 请求地址
 * @param {Array|Object} spec.data 请求数据
 * @param {String} [spec.target=''] 目标 iframe 名称
 * @param {String} [spec.method='post'] 请求方式
 * @param {String} [spec.acceptCharset=''] 请求目标的编码
 * @param {String} [spec.jsonp='callback'] 传递给接口的回调参数名称
 * @param {String} [spec.jsonpMethod=''] 传递给接口的回调参数的传递方式,可选['post', 'get']
 * @param {String} [spec.jsonpCallback=''] 传递给接口的回调函数名称,默认自动生成
 * @param {String} [spec.jsonpAddParent=''] 传递给接口的回调函数名称需要附带的前缀调用路径
 * @param {Function} [spec.complete] 获得数据的回调函数
 * @param {Function} [spec.success] 成功获得数据的回调函数
 * @example
 * var $iframePost = require('@spore-ui/kit/packages/io/iframePost');
 * document.domain = 'qq.com';
 * iframePost({
 *   url: 'http://a.qq.com/form',
 *   data: [{
 *     n1: 'v1',
 *     n2: 'v2'
 *   }],
 *   success: function (rs) {
 *     console.info(rs);
 *   }
 * });
 */
 
var hiddenDiv = null;
 
function get$() {
  var $;
  Eif (typeof window !== 'undefined') {
    $ = window.$ || window.jQuery || window.Zepto;
  }
  Iif (!$) {
    throw new Error('Need winddow.$ like jQuery or Zepto.');
  }
  return $;
}
 
function getHiddenBox() {
  var $ = get$();
  if (hiddenDiv === null) {
    hiddenDiv = $('<div/>').css('display', 'none');
    hiddenDiv.appendTo(document.body);
  }
  return hiddenDiv;
}
 
function getForm() {
  var $ = get$();
  var form = $('<form style="display:none;"></form>');
  form.appendTo(getHiddenBox());
  return form;
}
 
function getHiddenInput(form, name) {
  var $ = get$();
  var input = $(form).find('[name="' + name + '"]');
  Eif (!input.get(0)) {
    input = $('<input type="hidden" name="' + name + '" value=""/>');
    input.appendTo(form);
  }
  return input;
}
 
function getIframe(name) {
  var $ = get$();
  var html = [
    '<iframe',
    'id="' + name + '" ',
    'name="' + name + '"',
    'src="about:blank"',
    'style="display:none;"></iframe>',
  ].join(' ');
  var iframe = $(html);
  iframe.appendTo(getHiddenBox());
  return iframe;
}
 
function iframePost(spec) {
  var $ = get$();
  var conf = $.extend({
    form: null,
    url: '',
    data: [],
    target: '',
    method: 'post',
    acceptCharset: '',
    jsonp: 'callback',
    jsonpMethod: '',
    jsonpCallback: '',
    jsonpAddParent: '',
    complete: $.noop,
    success: $.noop,
  }, spec);
 
  var that = {};
  that.url = conf.url;
 
  that.jsonp = conf.jsonp || 'callback';
  that.method = conf.method || 'post';
  that.jsonpMethod = $.type(conf.jsonpMethod) === 'string'
    ? conf.jsonpMethod.toLowerCase()
    : '';
 
  var form = $(conf.form);
  Eif (!form.length) {
    form = getForm();
 
    var html = [];
    if ($.isArray(conf.data)) {
      $.each(conf.data, function (index, item) {
        Iif (!item) {
          return;
        }
        var inputHtml = [
          '<input',
          'type="hidden"',
          'name="' + item.name + '"',
          'value="' + item.value + '">',
        ].join(' ');
        html.push(inputHtml);
      });
    } else Eif ($.isPlainObject(conf.data)) {
      $.each(conf.data, function (name, value) {
        var inputHtml = [
          '<input',
          'type="hidden"',
          'name="' + name + '"',
          'value="' + value + '">',
        ].join(' ');
        html.push(inputHtml);
      });
    }
    $(html.join('')).appendTo(form);
  }
  that.form = form;
  that.conf = conf;
 
  var timeStamp = +new Date();
  var iframeName = 'iframe' + timeStamp;
 
  that.timeStamp = timeStamp;
  that.iframeName = iframeName;
 
  if (conf.acceptCharset) {
    form.attr('accept-charset', conf.acceptCharset);
    that.acceptCharset = conf.acceptCharset;
  }
 
  var iframe = null;
  var target = '';
  if (conf.target) {
    target = conf.target;
    Eif (['_blank', '_self', '_parent', '_top'].indexOf(conf.target) < 0) {
      iframe = $('iframe[name="' + conf.target + '"]');
    }
  } else {
    target = iframeName;
    iframe = getIframe(iframeName);
  }
  form.attr('target', target);
  that.target = target;
  that.iframe = iframe;
 
  var jsonpCallback = conf.jsonpCallback || 'iframeCallback' + timeStamp;
  that.jsonpCallback = jsonpCallback;
 
  if (!that.jsonpMethod || that.jsonpMethod === 'post') {
    var input = getHiddenInput(form, that.jsonp);
    input.val(conf.jsonpAddParent + jsonpCallback);
  } else Eif (that.jsonpMethod === 'get') {
    that.url = that.url
      + (that.url.indexOf('?') >= 0 ? '&' : '?')
      + that.jsonp
      + '='
      + jsonpCallback;
  }
 
  Eif (!conf.jsonpCallback) {
    that.callback = function (rs) {
      Eif ($.isFunction(conf.success)) {
        conf.success(rs, that, 'success');
      }
      Eif ($.isFunction(conf.complete)) {
        conf.complete(rs, that, 'success');
      }
    };
    window[jsonpCallback] = that.callback;
  }
 
  form.attr({
    action: that.url,
    method: that.method,
  });
 
  form.submit();
 
  return that;
}
 
module.exports = iframePost;