mui 浏览器跨域实现

时间:2020-12-25 17:08:23

from:http://ask.dcloud.net.cn/question/17373

APP开发时 是不需要JSONP支持的 mui本身就支持 但是 如果是微信或者浏览器的普通模式就不支持。所以贴出以下代码 大家可参考使用。(参考了zepto)

var jsonpID = 0;
$
.ajaxJSONP = function(url, options){
if (typeof url === "object") {
options
= url;
url
= undefined;
}
var options = $.extend({}, options || {})
for (var key in $.ajaxSettings) {
if (options[key] === undefined) {
options
[key] = $.ajaxSettings[key];
}
}
options
.url = appendQuery(options.url, '_=' + Date.now())

options
.url = appendQuery(options.url,
options
.jsonp ? (options.jsonp + '=?') : options.jsonp === false ? '' : 'callback=?')
var _callbackName = options.jsonpCallback,
callbackName
= ($.isFunction(_callbackName) ?
_callbackName
() : _callbackName) || ('jsonp' + (++jsonpID)),
script
= document.createElement('script'),
originalCallback
= window[callbackName],
responseData
,
abort
= function(errorType) {
script
.parentNode.removeChild(script)
if (callbackName in window) window[callbackName] = empty
ajaxComplete
('abort', xhr, options)
},
xhr
= { abort: abort }, abortTimeout;
if (options.error) script.onerror = function() {
xhr
.abort()
options
.error()
}

window
[callbackName] = function(data){
clearTimeout
(abortTimeout)
script
.parentNode.removeChild(script)
delete window[callbackName]
ajaxSuccess
(data, xhr, options)
}

serializeData
(options)
script
.src = options.url.replace(/=\?/, '=' + callbackName)
document
.head.appendChild(script)

if (options.timeout > 0) abortTimeout = setTimeout(function(){
xhr
.abort()
ajaxComplete
('timeout', xhr, options)
}, options.timeout)
return xhr
}