好久之前用過這個純js的ajax 當時只是初識js。jquery當時徹底不會用。。。隨着時間的慢慢過去。。。如今基本都直接jquery ajax很是的好用。今天有幸看到收藏下來 畢竟是經典呀~~(再次註明非原著)jquery
/**
* 獲得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>asdfasdfasdf<\/userid><\/user>";//"\/"這不是大寫V而是轉義是左斜槓和右斜槓
return xml;
}
//這就是參數
function createjson(){
var json={id:0,username:"好人"};
return json;
}
function c(){
alert("");
}
//測試
ajaxrequest("http://www.baidu.com","post",true,createxml(),c,document);ajax