標籤:request erro data ams code append ajax 參數 send
function AJAX(obj){
//做網路請求的時候參數以對象的形式傳遞進來
//我們規定obj裡麵包含屬性:url,
//請求方式type,
//date前端給後端傳遞的參數
//回呼函數success
//回呼函數error
//跨域的回呼函數----callBack
//後台接受回呼函數的key值
if (obj.callBack&&obj.key) {
var sc=document.createElement("script");
document.documentElement.appendChild(sc);
sc.src=obj.url+"?"+obj.key+"=callBack";
return;
}
var ajaxObj=null;
if (window.XMLHttpRequest) {
ajaxObj=new XMLHttpRequest();
}else{
ajaxObj=new ActiceXObject("Microsoft.XMLHTTP");
}
ajaxObj.onreadystatechange=function(){
if (ajaxObj.readyState==4) {
if (ajaxObj.status>=200 && ajaxObj.status<300|| ajaxObj.status == 304) {
if (obj.success) {
// obj.success(JSON.parse(ajaxObj.responseText));
obj.success(ajaxObj.responseText);
}
}else{
if (obj.error) {obj.error();}
}
}
}
// type轉化為小寫
var type=obj.type||"get";
type=type.toLowerCase();
var params="";
if (obj.data) {
for(var key in obj.data){
params+=key+"="+obj.data[key]+"&";
}
params.slice(0,params.length-1);
}
if (type=="get") {
//判斷是否傳遞了參數
ajaxObj.open(type,obj.url+"?"+params,true);
ajaxObj.send();
}else{
ajaxObj.open(type,obj.url,true);
ajaxObj.setRequestHeader("Content=Type","application/x-www-form-urlencoded");
ajaxObj.send(params);
}
}
Ajax前後台互動函數