原生ajax方法
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 }