1. 程式人生 > >原生和jQuery的ajax用法

原生和jQuery的ajax用法

style query nbsp 發送 scrip 格式 console spa 正在

jQuery的ajax方法:

$.ajax({
    url:‘/comm/test1.php‘,
    type:‘POST‘, //GET
    async:true,    //或false,是否異步
    data:{
        name:‘yang‘,age:25
    },
    timeout:5000,    //超時時間
    dataType:‘json‘,    //返回的數據格式:json/xml/html/script/jsonp/text
    beforeSend:function(xhr){
        console.log(xhr)
        console.log(
‘發送前‘) }, success:function(data,textStatus,jqXHR){ console.log(data) console.log(textStatus) console.log(jqXHR) }, error:function(xhr,textStatus){ console.log(‘錯誤‘) console.log(xhr) console.log(textStatus) }, complete:function(){ console.log(
‘結束‘) } })

原生的ajax方法:

$(‘#send‘).click(function(){
    //請求的5個階段,對應readyState的值
        //0: 未初始化,send方法未調用;
        //1: 正在發送請求,send方法已調用;
        //2: 請求發送完畢,send方法執行完畢;
        //3: 正在解析響應內容;
        //4: 響應內容解析完畢;

    var data = ‘name=yang‘;
    var xhr = new XMLHttpRequest();        //創建一個ajax對象
    xhr.onreadystatechange = function
(event){ //對ajax對象進行監聽 if(xhr.readyState == 4){ //4表示解析完畢 if(xhr.status == 200){ //200為正常返回 console.log(xhr) } } }; xhr.open(‘POST‘,‘url‘,true); //建立連接,參數一:發送方式,二:請求地址,三:是否異步,true為異步 xhr.setRequestHeader(‘Content-type‘,‘application/x-www-form-urlencoded‘); //可有可無 xhr.send(data); //發送 });

原生和jQuery的ajax用法