jQuery封装的ajxa

最基础的调用

$.ajax('add.php',{
    type:'post',
    success:function(res){
        //这里res拿到的只是响应体
    }
})

 dataType用于设置响应体的类型,一旦设置dataType选项,就不在关心服务端响应的content-type了

success函数中的res会自动根据服务端响应的content-type自动转换为对象

$.ajax({
    url:'add.php',
    type:'get',
    data:{id:1,name:'zx'},
    dataType:'json',
    success:function(res){
        
    
    }
})
  $.ajax({
            url:'add.php',
            type:'get',
            beforeSend:function(xhr){
                // 在所有发送请求的操作之前执行(open send)
                console.log(xhr)
            },
            success:function(res){
                // 只有请求成功(状态码为200) 才会执行这个函数
                console.log(res)
            },
            error:function(xhr){
                // 只有请求不正常才会执行(状态码不为200)
                console.log(xhr)
            },
            complete:function(xhr){
                // 不管是成功还是失败都是完成,都会执行这个complete函数
                console.log(xhr)
            }

        })

get、getJSON、post

$.get('add.php',{di:1},function(res){
            console.log(res)
        })

        $.post('add.php',{di:1},function(res){
            console.log(res)
        })

        $.getJSON('add.php',function (res) { 
            console.log(res)
         })

全局ajax事件处理函数

只要有ajax的请求发生就会自动调用函数

 $(document).ajaxStart(function () { 
            // 只要有ajax请求发生  就会执行
         })

         $(document).ajaxStop(function(){
            //  只要要ajax请求结束,就会执行
         })

猜你喜欢

转载自blog.csdn.net/qq_44313091/article/details/103347100