为自己而闪耀
为自己而闪耀
  • 发布:2014-10-22 15:20
  • 更新:2014-11-12 16:22
  • 阅读:3671

mui 自带的ajax可以用吗? 有没有例子,

分类:MUI
2014-10-22 15:20 负责人:无 分享
已邀请:
伟子

伟子

{{{
;(function($){
var jsonpID = 0,
document = window.document,
key,
name,
rscript = /<script\b[^<](?:(?!<\/script>)<[^<])<\/script>/gi,
scriptTypeRE = /^(?:text|application)\/javascript/i,
xmlTypeRE = /^(?:text|application)\/xml/i,
jsonType = 'application/json',
htmlType = 'text/html',
blankRE = /^\s
$/

// Number of active Ajax requests
$.active = 0;

function ajaxSuccess(data, xhr, settings) {
var context = settings.context, status = 'success';
settings.success.call(context, data, status, xhr);
ajaxComplete(status, xhr, settings);
}
// type: "timeout", "error", "abort", "parsererror"
function ajaxError(error, type, xhr, settings) {
var context = settings.context;
settings.error.call(context, xhr, type, error);
ajaxComplete(type, xhr, settings);
}
// status: "success", "notmodified", "error", "timeout", "abort", "parsererror"
function ajaxComplete(status, xhr, settings) {
var context = settings.context;
settings.complete.call(context, xhr, status);
}

// Empty function, used as default callback
function empty() {}

$.ajaxJSONP = function(options){
if (!('type' in options)) return $.ajax(options)

var callbackName = 'dhjsonp' + (++jsonpID),  
  script = document.createElement('script'),  
  cleanup = function() {  
    clearTimeout(abortTimeout);  
    if(!window[callbackName]) return;  
    document.querySelector('head').removeChild(script);  
    //$(script).remove();  
    delete window[callbackName];  
  },  
  abort = function(type){  
    cleanup();  
    // In case of manual abort or timeout, keep an empty function as callback  
    // so that the SCRIPT tag that eventually loads won't result in an error.  
    if (!type || type == 'timeout') window[callbackName] = empty  
    ajaxError(null, type || 'abort', xhr, options)  
  },  
  xhr = { abort: abort }, abortTimeout;  

window[callbackName] = function(data){  
  cleanup();  
  ajaxSuccess(data, xhr, options);  
}  

script.onerror = function() { abort('error') }  

script.src = options.url.replace(/=\?/, '=' + callbackName);  
document.querySelector('head').appendChild(script);  
//$('head').append(script);  

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

return xhr  

}

$.ajaxSettings = {
// Default type of request
type: 'GET',
// Callback that is executed before request
beforeSend: empty,
// Callback that is executed if the request succeeds
success: empty,
// Callback that is executed the the server drops error
error: empty,
// Callback that is executed on request complete (both: error and success)
complete: empty,
// The context for the callbacks
context: null,
// Whether to trigger "global" Ajax events
global: true,
// Transport
xhr: function () {
return new window.XMLHttpRequest()
},
// MIME types mapping
accepts: {
script: 'text/javascript, application/javascript',
json: jsonType,
xml: 'application/xml, text/xml',
html: htmlType,
text: 'text/plain'
},
// Whether the request is to another domain
crossDomain: false,
// Default timeout
timeout: 0,
// Whether data should be serialized to string
processData: true,
// Whether the browser should be allowed to cache GET responses
cache: true,
}

function mimeToDataType(mime) {
if (mime) mime = mime.split(';', 2)[0];
return mime && ( mime == htmlType ? 'html' :
mime == jsonType ? 'json' :
scriptTypeRE.test(mime) ? 'script' :
xmlTypeRE.test(mime) && 'xml' ) || 'text';
}

function appendQuery(url, query) {
return (url + '&' + query).replace(/[&?]{1,2}/, '?')
}

// serialize payload and append it to the URL for GET requests
function serializeData(options) {
if (options.processData && options.data && typeof options.data != "string")
options.data = $.param(options.data, options.traditional)
if (options.data && (!options.type || options.type.toUpperCase() == 'GET'))
options.url = appendQuery(options.url, options.data)
}

$.ajax = function(options){
var settings = $.extend({}, options || {});
for (key in $.ajaxSettings) if (settings[key] === undefined) settings[key] = $.ajaxSettings[key];

if (!settings.crossDomain) settings.crossDomain = /^([\w-]+:)?\/\/([^\/]+)/.test(settings.url) &&  
  RegExp.$2 != window.location.host  

if (!settings.url) settings.url = window.location.toString();  
serializeData(settings);  
if (settings.cache === false) settings.url = appendQuery(settings.url, '_=' + Date.now());  

var dataType = settings.dataType, hasPlaceholder = /=\?/.test(settings.url);  
if (dataType == 'jsonp' || hasPlaceholder) {  
  if (!hasPlaceholder) settings.url = appendQuery(settings.url, 'callback=?')  
  return $.ajaxJSONP(settings)  
}  

var mime = settings.accepts[dataType],  
    baseHeaders = { },  
    protocol = /^([\w-]+:)\/\//.test(settings.url) ? RegExp.$1 : window.location.protocol,  
    xhr = settings.xhr(), abortTimeout;  

if (!settings.crossDomain) baseHeaders['X-Requested-With'] = 'XMLHttpRequest'  
if (mime) {  
  baseHeaders['Accept'] = mime  
  if (mime.indexOf(',') > -1) mime = mime.split(',', 2)[0]  
  xhr.overrideMimeType && xhr.overrideMimeType(mime)  
}  
if (settings.contentType || (settings.contentType !== false && settings.data && settings.type.toUpperCase() != 'GET'))  
  baseHeaders['Content-Type'] = (settings.contentType || 'application/x-www-form-urlencoded')  
settings.headers = $.extend(baseHeaders, settings.headers || {});  

xhr.onreadystatechange = function(){  
  if (xhr.readyState == 4) {  
    xhr.onreadystatechange = empty;  
    clearTimeout(abortTimeout)  
    var result, error = false  
    if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304 || (xhr.status == 0 && protocol == 'file:')) {  
      dataType = dataType || mimeToDataType(xhr.getResponseHeader('content-type'));  
      result = xhr.responseText;  

      try {  
        if (dataType == 'script')    (1,eval)(result);  
        else if (dataType == 'xml')  result = xhr.responseXML;  
        else if (dataType == 'json') result = blankRE.test(result) ? null : $.parseJSON(result);  
      } catch (e) { error = e }  

      if (error) ajaxError(error, 'parsererror', xhr, settings)  
      else ajaxSuccess(result, xhr, settings)  
    } else {  
      ajaxError(null, xhr.status ? 'error' : 'abort', xhr, settings)  
    }  
  }  
}  

var async = 'async' in settings ? settings.async : true;  
xhr.open(settings.type, settings.url, async);  

for (name in settings.headers) xhr.setRequestHeader(name, settings.headers[name]);  

if (settings.timeout > 0) abortTimeout = setTimeout(function(){  
    xhr.onreadystatechange = empty;  
    xhr.abort();  
    ajaxError(null, 'timeout', xhr, settings);  
  }, settings.timeout);  

// avoid sending empty string (#319)  
xhr.send(settings.data ? settings.data : null);  
return xhr  

}

// handle optional data/success arguments
function parseArguments(url, data, success, dataType) {
var hasData = !$.isFunction(data);
return {
url: url,
data: hasData ? data : undefined,
success: !hasData ? data : $.isFunction(success) ? success : undefined,
dataType: hasData ? dataType || success : success
}
}

$.get = function(url, data, success, dataType){
return $.ajax(parseArguments.apply(null, arguments))
}

$.post = function(url, data, success, dataType){
var options = parseArguments.apply(null, arguments);
options.type = 'POST';
return $.ajax(options)
}

$.getJSON = function(url, data, success){
var options = parseArguments.apply(null, arguments);
options.dataType = 'json';
return $.ajax(options)
}

$.load = function(url, data, success){
if (!this.length) return this
var self = this, parts = url.split(/\s/), selector,
options = parseArguments(url, data, success),
callback = options.success
if (parts.length > 1) options.url = parts[0], selector = parts[1]
options.success = function(response){
self.html(selector ?
$('<div>').html(response.replace(rscript, "")).find(selector)

response) callback && callback.apply(self, arguments)
}
$.ajax(options);
return this
}

var escape = encodeURIComponent

function serialize(params, obj, traditional, scope){
var type, array = obj instanceof Array;
$.each(obj, function(key, value) {
type = value instanceof Array ? 'array' : typeof value;
if (scope) key = traditional ? scope : scope + '[' + (array ? '' : key) + ']'
// handle data in serializeArray() format
if (!scope && array) params.add(value.name, value.value);
// recurse into nested objects
else if (type == "array" || (!traditional && type == "object"))
serialize(params, value, traditional, key)
else params.add(key, value)
})
}

$.param = function(obj, traditional){
var params = [];
params.add = function(k, v){ this.push(escape(k) + '=' + escape(v)) }
serialize(params, obj, traditional)
return params.join('&').replace(/%20/g, '+')
}
})(gyp);
}}}

DCloud_UNI_CHB

DCloud_UNI_CHB

mui v0.7.0版本正式发布了mui模块,并在hello mui中增加了使用示例;

  • 石头茨

    官方提供的ajax.html实例,在谷歌PC版浏览器中使用,点击发送请求按钮没有效果。

    2014-11-22 12:04

该问题目前已经被锁定, 无法添加新回复