1 function ajax(options){ 2 options = options || {}; 3 var method = (options.type || "GET").toupperCase(), 4 url = options.url, 5 queryString = null; 6 if(!url) 7 return; 8 if(options.data){ 9 queryString = []; 10 for(var attr in options.data){ 11 queryString.push(attr + "=" +options.data[attr]); 12 } 13 queryString = queryString.join("&"); 14 } 15 if(method === "GET" && queryString){ 16 url += "?"+queryString; 17 queryString = ""; 18 } 19 var xhr = new XMLHttpRequest(); 20 xhr.open(method,url,true); 21 if(method === "POST") 22 xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 23 xhr.send(queryString); 24 xhr.onreadystatechange = function(){ 25 if(xhr.readyState === 4){ 26 if(xhr.status === 200){ 27 var data = xhr.responseText; 28 if(options.dataType === "json") 29 data = JSON.parse(data); 30 options.success && options.success(data); 31 }else{ 32 options.error && options.error(xhr.status); 33 } 34 } 35 } 36 }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。