跨浏览器Ajax调用封装
生活随笔
收集整理的這篇文章主要介紹了
跨浏览器Ajax调用封装
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
2019獨角獸企業重金招聘Python工程師標準>>>
/*** 執行基本ajax請求,返回XMLHttpRequest* Ajax.request(url,{* async 是否異步 true(默認)* method 請求方式 POST or GET(默認)* data 請求參數 (鍵值對字符串)* success 請求成功后響應函數,參數為xhr* failure 請求失敗后響應函數,參數為xhr* });**/ Ajax = function(){function request(url,opt){function fn(){}var async = opt.async !== false,method = opt.method || 'GET',data = opt.data || null,success = opt.success || fn,failure = opt.failure || fn;method = method.toUpperCase();if(method == 'GET' && data){url += (url.indexOf('?') == -1 ? '?' : '&') + data;data = null;}var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');xhr.onreadystatechange = function(){_onStateChange(xhr,success,failure);};xhr.open(method,url,async);if(method == 'POST'){xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded;');}xhr.send(data);return xhr; }function _onStateChange(xhr,success,failure){if(xhr.readyState == 4){var s = xhr.status;if(s>= 200 && s < 300){success(xhr);}else{failure(xhr);}}else{}}return {request:request}; }();調用方式
?
Ajax.request('servlet/ServletJSON',{data : 'name=jack&age=20',success : function(xhr){//to do with xhr},failure : function(xhr){//to do with xhr}} );轉載于:https://my.oschina.net/astrongpig/blog/29317
總結
以上是生活随笔為你收集整理的跨浏览器Ajax调用封装的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: bzImage的概要生成过程
- 下一篇: 文件操作一