'f'
mh-two-thousand-and-two
2024-04-12 26f2711ef9461961fb953e2b497bd314ef95e345
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
/**
 * JSONP请求
 * @param {string} url 请求的地址
 * @param {object} options 请求的参数
 * @param {Function} success 请求成功的回调
 * @param {Function} error 请求失败的回调
 */
export function getJSONP (url, options, success, error) {
  var js = document.createElement('script')
  var callbackKey = options.callback || 'callback'
  var callbackName = '__callback' + Date.now() + Math.random().toString().slice(2)
  var timeout = options.timeout || 30000
  var timing
  function end () {
    clearTimeout(timing)
    delete window[callbackName]
    js.remove()
  }
  window[callbackName] = (res) => {
    if (typeof success === 'function') {
      success(res)
    }
    end()
  }
  js.onerror = () => {
    if (typeof error === 'function') {
      error()
    }
    end()
  }
  timing = setTimeout(function () {
    if (typeof error === 'function') {
      error()
    }
    end()
  }, timeout)
  js.src = url + (url.indexOf('?') >= 0 ? '&' : '?') + callbackKey + '=' + callbackName
  document.body.appendChild(js)
}