标题 | 纯JavaScript实现AJAX |
范文 | 纯JavaScript实现AJAX。具体代码如下: window.lcq = {}; (function(obj) { obj = {}; //创建xmlhttprequest对象 obj.createXMLHttpRequest = function() { if (window.ActiveXObject) { var aVersions = ["MSXML2.XMLHttp.5.0", "MSXML2.XMLHttp.4.0", "MSXML2.XMLHttp.3.0", "MSXML2.XMLHttp", "Microsoft.XMLHttp"]; for (var i = 0; i < aVersions.length; i++) { try { return new ActiveXObject(aVersions[i]); } catch (oError) { continue; } } } else if (window.XMLHttpRequest) { return new XMLHttpRequest(); } throw new Error("XMLHttp object could not be created."); } //ajax obj._xmlHttp = null; obj.ajax = function(options) { try { obj._xmlHttp = this.createXMLHttpRequest(); obj._xmlHttp.open(options.method, options.url, true); obj._xmlHttp.setRequestHeader("cache-control", "no-cache"); obj._xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); obj._xmlHttp.onreadystatechange = function() { if (obj._xmlHttp.readyState == 4) { if (obj._xmlHttp.status == 200) { var _response = ""; switch (options.dataType.toLowerCase()) { case "json": _response = eval(obj._xmlHttp.responseText); break; case "xml": _response = obj._xmlHttp.responseXML; break; case "html": _response = obj._xmlHttp.responseText; break; default: _response = obj._xmlHttp.responseText; break; } options.success(_response); } } else { } } obj._xmlHttp.send(options.data); } catch (e) { } } //提示信息的方法 obj.show = function(message) { alert(message); } //对象引用 lcq = obj; $ = obj; })(lcq); //简单的用法 function _testAjax(obj) { obj.disabled = true; obj.value = "正在提交......"; $.ajax({ url: "/xmls/url.xml", method: "GET", data: "", dataType: "html", success: function(response) { obj.disabled = false; obj.value = "处理完毕"; //show(response); }, error: function(response) { alert(response); } }); } function show(message) {document.getElementById("wraper").innerHTML = message;} //html部分 <div id="wraper"> </div> <input type="button" value="Ajax测试" onclick="_testAjax(this);" /> |
随便看 |
|
在线学习网范文大全提供好词好句、学习总结、工作总结、演讲稿等写作素材及范文模板,是学习及工作的有利工具。