/** * 獲得ajax對象 */ function getajaxHttp() { var xmlHttp; try { // Firefox, Opera 8.0+, Safari xmlHttp = new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("您的瀏覽器不支持AJAX!"); return false; } } } return xmlHttp; } /** * 發送ajax請求 * url--url * methodtype(post/get) * con (true(異步)|false(同步)) * parameter(參數) * functionName(回調方法名,不須要引號,這裏只有成功的時候才調用) * (注意:這方法有二個參數,一個就是xmlhttp,一個就是要處理的對象) * obj須要到回調方法中處理的對象 */ function ajaxrequest(url,methodtype,con,parameter,functionName,obj){ var xmlhttp=getajaxHttp(); xmlhttp.onreadystatechange=function(){ if(xmlhttp.readyState==4){ //HTTP響應已經徹底接收才調用 functionName(xmlhttp,obj); } }; xmlhttp.open(methodtype,url,con); xmlhttp.send(parameter); } //這就是參數 function createxml(){ var xml="<user><userid>haorooms 純js ajax請求<\/userid><\/user>";//"\/"這不是大寫V而是轉義是左斜槓和右斜槓 return xml; } //這就是參數 function createjson(){ var json={id:0,username:"haorooms"}; return json; } function c(){ alert(""); } //測試 ajaxrequest("http://www.haorooms.com","post",true,createxml(),c,document);