Ajax原理及代码封装
发布时间:2020-12-16 03:19:30 所属栏目:百科 来源:网络整理
导读:var xmlhttp;if (window.XMLHttpRequest) { // code for IE7+,Firefox,Chrome,Opera,Safari xmlhttp = new XMLHttpRequest();} else { // code for IE6,IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");}xmlhttp.onreadystatechange = function() { i
var xmlhttp; if (window.XMLHttpRequest) { // code for IE7+,Firefox,Chrome,Opera,Safari xmlhttp = new XMLHttpRequest(); } else { // code for IE6,IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200){ // to do... } } xmlhttp.open("GET","test1.txt",true); xmlhttp.send(); 步骤:1、创建。创建 var = new XMLHttpRequest(); 老版本的 Internet Explorer (IE5 和 IE6)使用 ActiveX 对象: var = new ActiveXObject("Microsoft.XMLHTTP"); 2、连接和发送。
3、接收。
只要
封装ajax方法:ajax({ url: "./test.php",type: "POST",data: { name: "abc",age: 18 },dataType: "json",success: function (response,xml) { // 执行成功回调 },fail: function (status) { // 执行失败回调 } }); function ajax(options) { options = options || {}; options.type = (options.type || "GET").toUpperCase(); options.dataType = options.dataType || "json"; var params = formatParams(options.data); // 创建对象 if (window.XMLHttpRequest) { var xhr = new XMLHttpRequest(); } else { var xhr = new ActiveXObject('Microsoft.XMLHTTP'); } //接收 - 第三步 xhr.onreadystatechange = function () { if (xhr.readyState == 4) { var status = xhr.status; if (status >= 200 && status < 300) { options.success && options.success(xhr.responseText,xhr.responseXML); } else { options.fail && options.fail(status); } } } //连接 和 发送 - 第二步 if (options.type == "GET") { xhr.open("GET",options.url + "?" + params,true); xhr.send(null); } else if (options.type == "POST") { xhr.open("POST",options.url,true); //设置表单提交时的内容类型 xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xhr.send(params); } //格式化参数 function formatParams(data) { var arr = []; for (var name in data) { arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name])); } arr.push(("v=" + Math.random()).replace(".","")); return arr.join("&"); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |