ajax相关

1.ajax的原生写法

function requestAjax(){
    var xmlhttp;
    if (window.XMLHttpRequest){
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();//创建ajax对象
    }else{
        // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    if(xmlhttp){
        xmlhttp.open("GET","/ajax/demo_get.asp",true);//使用get方式与服务器建立连接
        
        xmlhttp.onreadystatechange=function(){
             //发送一个请求后,客户端无法确定什么时候会完成这个请求,所以需要用事件机制来捕获请求的状态,XMLHttpRequest对象提供了onreadyStateChange事件实现这一功能。
            //onreadyStateChange事件是在readyState属性发生改变时触发的,readyState的值表示了当前请
            if (xmlhttp.readyState==4 && xmlhttp.status==200){
                //responseText 请求成功后获取数据
                ocument.getElementById("myDiv").innerHTML=xmlhttp.responseText;
            }
        }
    }    
    xmlhttp.send();//发送请求
}  

2.jq的ajax写法

$.ajax({
   type:"post", //请求方式(get和post),默认为get
   url:url,//请求的url地址
   dataType:"json", //返回格式为json
   async:true//请求是否异步,默认为异步,这也是ajax重要特性,false为同步
   data:{"id":"001","name":"tom"}, //参数值(此处不是json对象,是json字符串,字符串。
   success:function(suc){ //请求成功时处理
         //对后台返回数据的处理
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
           alert(XMLHttpRequest.status);//状态码
           alert(XMLHttpRequest.readyState);//状态
           alert(textStatus);//错误信息
     }
});

 

原文地址:https://www.cnblogs.com/wgl0126/p/9240039.html