原生Ajax和JQuery Ajax

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34461514/article/details/79373089

XHR,原生js方式

获取XHR对象

var xhr=false;
if(window.XMLHttpRequest){
    xhr = new XMLHttpRequest();
}else{
    xhr = new ActiveXObject('Microsoft.XMLHTTP');
}

发送数据示例

//再三确认
if(XHR==false){
    var uri="sign.action";
    XHR.open("post",uri,true);
    XHR.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    XHR.send("date="+date);
    XHR.onreadystatechange=signResult;
}
else
    alert("XHR is NULL");

接收数据示例

function signResult(){
    if(XHR.readyState==4 && XHR.status==200){
        if(!XHR.responseText)
            alert("...")
        else{
        ...
        }   
    }
}

JQuery的方式

get、post方式

$.get(action,function(result,statu){
    switch(statu){
    case "success":
        ...
    }
},"json");

$.post(action,function(result,statu){
    switch(statu){
    case "success":
        ...
    }
},"json");

ajax方式

//dateType为返回的数据类型
$.ajax({
    url:url,
    type:"POST",
    data:data,
    timeout:30000,
    dataType:'json',
    success:success,
    error:function(xhr,status){
        console.log(url+"数据获取错误:"+status);
    }
})

附:获取项目根目录的方法

function getRootPath_dc() {
    var pathName = window.location.pathname.substring(1);
    var webName = pathName == '' ? '' : pathName.substring(0, pathName.indexOf('/'));
    if (webName == "") {
        return window.location.protocol + '//' + window.location.host;
    }
    else {
        return window.location.protocol + '//' + window.location.host + '/' + webName;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_34461514/article/details/79373089