ajax中get和post的提交、却别、错误处理以及注意事项

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    $.get和$.post的不同
    1、get通过url提交的,post是通过http消息实体提交的
    2、get提交大小限制为2kb,post不限制
    3、get提交会被缓存下来,有安全隐患,post没有
    4、get通过$_get[],而post通过$_POSt[]获取




    $.get 和 $.post的几种传参方式
    1、在url后面直接问号传参: test.php?age=20
    2、以字符串键值对的方式传参:  'age=20'
    3、以对象键值对的方式传参:  {age:20}


    $.get 以上三种方式都支持,但是$.post和$.ajax只支持后2种写法


    具体demo:
    1、$.get('test.php?age=20',function(result){
        alert(result)
    })
    2、$.get('test.php','age=20',function(result){
        alert(result)
    })
    3、$.get('test.php',{age:20},function(result){
        alert(result)
    })


    ,php文件异步请求默认返回的是text或html的type类型,如果返回的是非json类型强制用type转成json类型可能会报错
    


   三、getScript 一般就是引入一个js文件
   $.getScript('demo.js') 即可 
   四:getScript 请求一个json文件,不必要指定返回的数据类型,而且如果制定了非json的type类型如type:html ,由于安全性高一点也不会返回html格式的数据


   五、在用ajax 提交表单的时候可以用表单序列化获取表单的传参内容,而且传参的形式是字符串键值对,并且还会对url进行编码
   $('form').serialize();
   如:$.ajax({
        type:'POST',
        url:'text.php',
        data: $('form').serialize(),
        success:function(response,status,xhr){
            dosomething...
        }  
   })


   五-1;在一下html中可以用decodeURLComponent对序列化的数据进行解码
   <form>
       <input type="checkbox" name="sex" value="男" id="">
       <input type="checkbox" name="sex" value="女" id="">
   </form>
   <div id="box"></div>
   <script>
        $('form input[name=sex]').click(function(){
            $('#box').html(decodeURLComponent($(this).serialize()))
        })
   </script>


   5-2,以上的例子可以用serializeArray()可将数据格式化为json格式


   六;ajaxSetup 是对ajax进行初始化,应用场景当多个ajax重复用到某些数据的时候可以分装起来如:
   $.ajaxSetup({
    type:'POST',
    url:'text.php',
    data:'{}'
   });
   $('form :submit').click(function(){
    $.ajax({
     success:function(response,status,xhr){


     }
    })
   });


   7.$.param()方法可对复杂的json进行字符串键值对解析r




   进阶:
   8、$.ajaxstart()和$.ajaxStop()放置加载时间过长处理
   在jq1.8版本后必须绑定在document上如:
   $(document).ajaxStart(function(){
        $('.loading').show()
   }).ajaxStop(function(){
         $('.loading').hide()
   });


   8-1 如果加载超时,可以用timeout设置超时限制


 ===============
    $.ajax进阶 
    1、加载请求
    $.ajaxStart() 、$.ajaxStop 可以在对用户等待时间加载loading图片


    2、错误处理
    $.ajax的错误处理  可以在自己当前添加error方法,参数是(xhr,status,statusText) 如:
    2-1: $.ajax的error处理
    $.ajax({
        url:'www.seogjgsdggd.com/test.php',
        type:'POST',
        data:'age=20',
        error:function(xhr,status,statusText){
            alert(xhr.status)
        }
    });
    2-1:$.post的error错误处理,添加连缀的局部方法error,参数是(xhr,errorText,errorType)如:
    $.post('test.php','age=20',function(response,status,xhr){
         alert(response+"//"+xhr.status)
    }).error(function(xhr,errorText,errorType){
        alert('错误')
    });
    也可以用全局的ajaxError方法如(1.8版本建议吧事件绑定在document上),但是参数有所不同(event,xhr,settings,errorType) 如:
    $(document).ajaxError(function(event,xhr,settings,errorType){
        event,xhr,settings都是对象,event一般就用(type,target)属性,settings一般就用(url,type);


    });




    3/ 请求全局事件有 $.ajaxstart(),$.ajaxstop()、$.ajaxError(),
                        $.ajaxSuccess(),$.ajaxComplete,$.ajaxSend()
        前三个是请求时出发的全局事件,
        $.ajaxSuccess() 对应一个局部方法 .success();
        $.ajaxComplete()对应一个局部方法 .complete();
        $.ajaxSend()没有对应的局部方法,只有属性beforeSend
        例子:
        $(document).ajaxSend(function(){
            alert(发送请求之前);
        }).ajaxComplete(function(){
             alert(请求成功和失败之后都会出现,是出现在成功或者失败的后面);
        }).ajaxSuccess(function(){
             alert(请求成功后);
        }).ajaxError(function(){
            alert(请求失败后);
        })


        $.post('test.php',$('form').serialize()).success(function(){
            alert(请求成功后);
        }).complete(function({
            alert(请求完成后);
        }).error(function(){
            alert(请求失败后);
        })


        $.ajax({
            url:'test.php',
            type:'POST',
            data:$('form').serialize(),
            success:function(response,status,xhr){
                alert(请求成功后);
            },
            complete:function(){
                alert(请求完成后);
            },
            error:function(xhr,errorText,errorType){
                alert(请求错误后);
            },
            beforSend:function(){
                alert(请求之前);
            }
        })


</body>
</html>
  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
AJAX,GET和POST是两种常见的请求方法。 1. GET请求:通过URL参数传递数据,将数据附加在URL的末尾。GET请求通常用于获取数据,不应该用于敏感信息的传递。GET请求的特点包括: - 数据以键值对的形式附加在URL后面,例如:`http://example.com/api?param1=value1&param2=value2` - GET请求对参数长度有限制,一般为2048个字符 - GET请求可以被缓存 - GET请求可以被收藏为书签 2. POST请求:通过HTTP消息体传递数据,将数据放在请求的消息体POST请求通常用于向服务器发送数据,包括敏感信息。POST请求的特点包括: - 数据不会附加在URL后面,而是通过消息体发送 - POST请求对参数长度没有限制 - POST请求不会被缓存 - POST请求不会被收藏为书签 在AJAX,使用GET和POST请求可以通过XMLHttpRequest对象或者fetch函数来实现。例如,在JavaScript使用XMLHttpRequest对象发送GET请求的示例代码如下: ```javascript var xhr = new XMLHttpRequest(); xhr.open('GET', 'http://example.com/api?param1=value1&param2=value2', true); xhr.onreadystatechange = function() { if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) { var response = xhr.responseText; // 处理响应数据 } }; xhr.send(); ``` 使用fetch函数发送POST请求的示例代码如下: ```javascript fetch('http://example.com/api', { method: 'POST', body: JSON.stringify({ param1: 'value1', param2: 'value2' }) }).then(function(response) { if (response.ok) { return response.json(); } else { throw new Error('Error: ' + response.status); } }).then(function(data) { // 处理响应数据 }).catch(function(error) { console.log(error); }); ``` 这些示例只是简单的演示,实际使用可能需要根据具体情况进行参数的设置和错误处理
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值