jquery ajax 笔记

$(function(){
    //jquery ajax----> html xml javascript css json  php sql
    
    //*****************************************************************************************************
    //load局部方法:适用静态文件异步获取,需要包含元素的jquery对象作前缀
    
    // $(':button[name=test]').click(function(){
        //带选择器的url
        // $('.art').children('p').last().load('html/test.html .url')
        
        //不传data,则默认get方式
        //$('.art').find('p').eq(1).load('php/get.php?url=baidu');
        
        //传data的post方式
        /* $('.load').load('php/post.php',{
            url:'baidu'
        }) */
        
        //ajsx方法,第三个参数callback回调函数
        /* $('.load').load('php/post.php',{
            url:'baidu_ajax',
        },function(response,status,xhr){  //callback 回调函数
            $(this).html('返回值'+response+',状态为'+status+',状态是'+xhr.statusText);
            //浏览器返回:返回值baidu_ajax,状态为success,状态是OK,其中status==success可以作判断用
            //其中xhr包含response,status,xhr.statusText,只是其中常用且重要的2个参数,所以单独提出来
            //xhr.responseText=response;xhr.status=200,http状态码200就是ok状态字符串
        }); */
    // });
    
    //*****************************************************************************************************
    
    
    //get全局方法
    
    //问号传参
    /* $(':button[name=test]').click(function(){
        $.get('php/get.php?url=baidu',function(response,status,xhr){
            $('.load').html(response);
        });
    }); */
    //字符串健值对,多个可以用&连接符如url=baidu&a=b,其实最终还是转化为问号传参
    /* $(':button[name=test]').click(function(){
        $.get('php/get.php','url=baidu&a=b',function(response,status,xhr){
            $('.load').html(response);
        });
    }); */
    //对象键值对传=>问号传参
    /* $(':button[name=test]').click(function(){
        $.get('php/get.php',{
            url:'baidu',
            a:'b',
        },function(response,status,xhr){
            $('.load').html(response);
        });
    }); */
    
    
    //*****************************************************************************************************
    
    
    //post全局方法,只能用字符串、对象键值对这两种方法,不再累赘。且不会在浏览器返回的报文中显示出来.
    
    // $.post()方法的使用和$.get()基本上一致,具体区别如下:
    // 1.GET 请求是通过URL 提交的,而POST 请求则是HTTP 消息实体提交的;
    // 2.GET 提交有大小限制(2KB),而POST 方式不受限制;
    // 3.GET 方式会被缓存下来,可能有安全性问题,而POST 没有这个问题;
    // 4.GET 方式通过$_GET[]获取,POST 方式通过$_POST[]获取。
    
    
    
    
    //*****************************************************************************************************
    
    
    //$.get和$.post方法的第4个参数type即服务器返回的内容格式,包括xml、html、script、json、jsonp 和text。
    
    /* $(':button[name=test]').click(function(){
        $.post('php/post.php',{
            url:'baidu_post'
        },function(response,status,xhr){
            $('.load').html(response);
        },'html');//'html'是第四个参数,智能判断,可以省略,默认是html或text
    }); */
    
    //如果默认是xml或是json文件,强行设置type为html,将会返回xml或json全部内容包含标签
    
    //可以先获取所有内容,然后通过选择器捕获相关内容。例如
    /* $(':button[name=test]').click(function(){
        $.post('json/test.json',function(response,status,xhr){
            $('.load').html(response[0].url);
        });
    }); */
    
    
    //*****************************************************************************************************
    
    
    //特定异步加载方法$.getScript()和$.getJSON();此处没有第4个参数type,接着上例
    /* $(':button').click(function(){
        $.getJSON('json/test.json?a=b&c=d',function(response,status,xhr){
            alert(response[0].url);
        });
    }); */
    //需要时加载js,例如实现某些功能的小插件
    /* $(':button').click(function(){
        $.getScript('js/test.js');
    }); */
    
    //*****************************************************************************************************
    
    
    
    
    //$.ajax方法,以上方法都是基于这个底层的封装
    
    /* $(':submit').click(function(e){
        // e.preventDefault(); //会使html5智能表单失效
        // e.stopPropagation();
        $.ajax({
            url:'php/test.php',
            type:'POST',
            //传统写法
            // data:{
                // user:$(':text').val(),
                // email:$('input[name=email]').val()
            // },
            
            //表单序列化serilize()
            data:$('#ff').serilize(),
            success:function(response,status,xhr){
                $('.load').html(response);
            }
        });
        // return false;//表单序列化后阻止submit提交无效
    }); */
    
    
    //*****************************************************************************************************
    
    
    //.serialize()方法,直接获取单选,多选和下拉列表等内容
    
    /*
    //单选
    
    $(':radio').click(function(){
        var content=$(this).serialize(),
            ctt=decodeURIComponent(content);//js解码方法
        $('.load').html(ctt);
    });
    //多选
    
    $(':checkbox').click(function(){
        var content=$(this).serialize();
        $('.load').html(content);
    });
    
    
    //单独获取下拉列表变化后选中的值
    
    //js方法
    function select_fn(){
        var slct=document.getElementById("slct");
        var str=[];
        for(i=0;i<slct.length;i++){
            if(slct.options[i].selected){
                str.push(slct[i].value);
            };
        };
        alert(str);
    };
    $(':submit').on('click',function(e){
        select_fn();
        e.preventDefault();
    });
    
    //.serializeArray()方法,返回json数据
    $(':submit').click(function(e){
        // console.log($('#slct').serializeArray());
        var slct_json=$('#slct').serializeArray();
        alert(slct_json[0].value);
        alert(slct_json[1].value);
        alert(slct_json[2].value);
    });
    */
    
    
    //*****************************************************************************************************
    
    //ajaxSetup初始化重复的参数,type,url,data等
    /* $(':submit').click(function(){
        $.ajaxSetup({
            type:'POST',
            url:'php/test.php',
            data:{
                user:$(':text[name=user]').val(),
                email:$('input[name=email]').val(),
            }
        });
        $.ajax({
            success:function(response,status,xhr){
                alert(response);
            },
        });
        return false;
    }); */
    
    //*****************************************************************************************************
    
    //$.param(obj),解析对象形式的键值对转为url字符串键值对
    /* var obj={a:1,b:2,c:3};
    var ff=$.param(obj);
    alert(ff);
    
    //serialize对复杂的表单能力有限,可采用$.param(obj)
    $(':submit').click(function(){
        $.ajaxSetup({
            type:'POST',
            url:'php/test.php',
            data:$.param({
                user:$(':text[name=user]').val(),
                email:$('input[name=email]').val(),
            }),
        });
        $.ajax({
            success:function(response,status,xhr){
                alert(response);
            },
        });
        return false;
    }); */
    
    //*****************************************************************************************************
    //加载请求
    /* $(':submit').click(function(e){
        //done,fail,always将会替代.success()、.error()和.complete()连缀的方法
        // $.ajax({
            // url:'php/test.php',
            // type:'POST',
            // data:$('#ff').serialize(),
        // })
        // .done(function(response,status,xhr){
            // alert(response);
        // });
        //done连缀方法
        // $.post('php/test.php',$('#ff').serialize())
        // .done(function(response,status,xhr){
            // alert(response);
        // });
        //加载提示,url不存在,加载.loading友好提示“努力加载中...”,如本地测试一闪而过
        //全局方法绑定在document上, .ajaxStart()-->请求开始、.ajaxStop()-->请求结束
        $.ajax({
            url:'http://www.errorwebsiteffaewfaegawefafwefdsafe118155691.cn/php/test.php',
            type:'POST',
            data:$.param({
                user:$(':text[name=user]').val(),
                email:$('input[name=email]').val()
            }),
            timeout:500,//设置超时
            global:false,//取消全局事件,不显示.loading内容
            success:function(response,status,xhr){
                alert(response);
            }
        });
        $(document).ajaxStart(function(){
            $('.loading').show();
        }).ajaxStop(function(){
            $('.loading').hide();
        });
        e.preventDefault();
    }); */
    
    //*****************************************************************************************************
    
    //错误处理
    //ajax属性方法
    /* $(':submit').click(function(){
        $.ajaxSetup({
            type:'POST',
            url:'php/test_err.php',//不存在这个文件
            data:$('#ff').serialize(),
        });
        $.ajax({
            beforeSend:function(xhr,settings){              //请求之前
                alert(xhr.readyState+'-'+settings.url)
            },
            error:function(xhr,errorText,errorType){        //错误
                alert(xhr.status+':'+xhr.status.Text);
                alert(errorText+':'+errorType);
            },
            success:function(response,status,xhr){          //成功
                alert(response);
            },
            complete:function(xhr,status){
                alert(xhr.responseText+'-'+status)          //不论成功与错误都返回值
            }
            
        });
        e.preventDefault();
    });
     */
    
     //$.post连缀方法.fail(),而.error()已弃用
     /* $(':submit').click(function(){
         $.post('php/test_err.php').fail(function(xhr,errorText,errorType){
             alert(errorText+':'+errorType);
             alert(xhr.status+':'+xhr.statusText);
         });
         return false;
     }); */
    
     //$.post()使用全局.ajaxError()事件,绑定在document上
     /* $.post('php/test_err.php');
     $(document).ajaxError(function(event,xhr,settings,errorType){
        // alert(event.type);
        // alert(event.target);
        // for(var i in settings){
            // document.write(i+"<br>")
        // };
        // alert(settings.url+';'+settings.type);
        alert(errorType);
     }); */
    
    //*****************************************************************************************************
    
    //ajax全局方法--->局部方法
    /* .ajaxSend--->无(只有属性beforeSend,见上文)
        .ajaxSuccess--->.done()
        .ajaxError--->.fail()
        .ajaxComplete()--->.always() */
        
    //局部
    /* $(':submit').click(function(){
        $.post('php/test_err.php')
        .done(function(response,status,xhr){
            alert('success!')
        })
        .fail(function(xhr,errorText,errorType){
            alert('error!')
        })
        .always(function(xhr,status){
            alert('complete!')
        });
        return false;
    }); */
    
    //全局
    /* $(':submit').click(function(){
        $.post('php/test_err.php',$('#ff').serialize())     //不存在这个文件test_err.php
    });
    
    $(document).ajaxSend(function(event,xhr,settings){      //请求之前
        alert('beforeSend!')
    })
    .ajaxError(function(event,xhr,settings,errorType){      //请求失败
        alert('fail!')
    })
    .ajaxSuccess(function(event,xhr,settings){              //test_err.php换成test.php,请求成功
        alert('done!')
    })
    .ajaxComplete(function(event,xhr,settings){             //请求完成,不论成与败都返回
        alert('always!')
    }); */
    
    //*****************************************************************************************************
    
    //$.ajax()加载JSON文件
    /* $(':submit').click(function(){
        $.ajax({
            type:'POST',
            url:'json/test.json',
            // dataType:'json',                                 //智能判断,不设置也可
            // dataType:'html',                                 //强行设置html返回test.json所有内容
            success:function(response,status,xhr){
                // alert(response[0].url)
                // alert(response);
            }
        });
        
    }); */
    //本地$.ajax()加载JSONP文件
    /* $(':submit').click(function(){
        $.ajax({
            type:'POST',
            url:'php/jsonp.php',
            dataType:'json',                                       //必须设置,php≠json
            success:function(response,status,xhr){
                alert(response.a);                                 //返回"1"
                alert(response.b);                                 //"2"
                alert(response.c);                                 //"3"
            }
        })
    }); */
    //$.ajax()获取远程数据
    /* $(':submit').click(function(){
        $.ajax({
            type:'POST',
            url:'http://www.?.com/php/jsonp2.php?callback=?',      //必须设置callback=?
            dataType:'json',                                       //必须设置,php≠json
            success:function(response,status,xhr){
                // alert(response);                                 
                console.log(response);                                 
                alert(response.c);                                 //"3"
            }
        })
    }); */
    //$.ajax()获取远程数据,jsonp方式
    /* $(':submit').click(function(){
        $.ajax({
            type:'POST',
            url:'http://www.?.com/php/jsonp2.php',                  //不加"callback=?"
            // dataType:'json',
            dataType:'jsonp',                                       //只在此外修改成'jsonp'即可
            success:function(response,status,xhr){
                // alert(response);                                 
                console.log(response);                                 
                alert(response.c);                                 //"3"
            }
        })
    }); */
    
    //*****************************************************************************************************
    
    //jqXHR=>XHR超集,可扩展性强,互不干扰,依次执行
    /* $(':submit').click(function(){
        var jqXHR=$.ajax({
            type:'POST',
            url:'php/test.php',
            data:$('#ff').serialize(),
            });                                            //可以连缀.done()
        jqXHR.done(function(response,status,xhr){          //依次执行
            alert(response+'------A');
        });    
        jqXHR.done(function(response,status,xhr){
            alert(response+'------B');
        });    
        return false;    
    }); */
    
    
    //jqXHR when方法
    /* $(':submit').click(function(){
        var jqXHR_1=$.ajax('php/t1.php');
        var jqXHR_2=$.ajax('php/t2.php');
         */
    //传统写法
        /* jqXHR_1.done(function(response){
            alert(response);
        });
        jqXHR_2.done(function(response){
            alert(response);
        });
         */
    //when方法    
        /* $.when(jqXHR_1,jqXHR_2).done(function(f1,f2){
            alert(f1);                                           
            alert(f2[0]);                                        //得到第一条数据
        }); */
    

    //测试this指向
    var obj={
        name:'china',
        test:function(){
            alert(this.name)                   //弹出:btn
            
            //js解决方法
            // var _this=obj;
            // alert(_this.name);           //弹出:china
        }
    };
    
    // $(':button[name=btn]').click(obj.test);     
    $(':button[name=btn]').click($.proxy(obj,'test'));
    
        
        
        
    });
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值