zoukankan      html  css  js  c++  java
  • 原生Ajax与jQuery的Ajax和伪Ajax

    用原生的ajax发送请求
               var xhr = new XMLHttpRequest();
                xhr.open('请求方式(post/get)', '请求url',true);
                xhr.onreadystatechange = function(){
                    if(xhr.readyState == 4){
                        // 接收完毕
                        var obj = JSON.parse(xhr.responseText); //获取请求回来的数据
                    }
                };
                xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset-UTF-8');
                xhr.send("发送的数据");
    
    用jQuery的Ajax发送请求
     $.ajax({
                    url: '/url/',
                    type: '请求方式',
                    data: 数据,
                    success:function(res){
                        
                    }
                })
    
    用伪Ajax
    <iframe id="ifm1" url='发起请求的url' style="display: none;"></iframe>
    
    如果伪Ajax先与form表单绑定发起伪ajax请求
    发送请求
        <form id="form1" action="发起请求的url" method="POST" enctype="multipart/form-data" target="与iframe的name绑定">
            <iframe id="ifm1" name="ifm1" style="display: none;"></iframe>
            <input type="file" name="fafafa" onchange="changeUpalod();" />
            <input type="submit" onclick="iframeSubmit();" value="Form提交"/>#}
        </form>
    获取返回的数据
            function iframeSubmit(){
                $('#ifm1').load(function(){
                    var text = $('#ifm1').contents().find('body').text();
                    var obj = JSON.parse(text);
                })
            }
    
    因为iframe里面的数据是服务端返回了才有,也就是说服务端返回就会触发onload事件,所以说我们可以在提交的时候给iframe绑定load事件,等服务器返回就会触发这个事件
    
    发送文件
    原生ajax
                var file_obj = document.getElementById('fafafa').files[0];
    
                var fd = new FormData();
                fd.append('fafafa',file_obj);
                fd.append('pwd','123')
    			xhr.send(fd);
    jQuery中的ajax
        function jqSubmit(){
                // $('#fafafa')[0]
                var file_obj = document.getElementById('fafafa').files[0];
    
                var fd = new FormData();
                fd.append('username','root');
                fd.append('fafafa',file_obj);
    
                $.ajax({
                    url: '/upload_file/',
                    type: 'POST',
                    data: fd,
                    processData: false,  // tell jQuery not to process the data
                    contentType: false,  // tell jQuery not to set contentType
                    success:function(arg);
                    }
                })
  • 相关阅读:
    Python 面向对象(一)
    【Python之搜索引擎】(一)概述
    【Python】回文palindrome——利用字符串反转
    【Python】raw转义字符
    【Python】directory字典类型
    【Python】面向对象编程思想
    【Python】Sublime text 3 搭建Python IDE
    【Python】卸载完Python3 之后 Python2 无法打开IDLE
    【Python】猜数小游戏(文件操作)
    【Python】list和tuple 区别比较
  • 原文地址:https://www.cnblogs.com/KingOfCattle/p/14312936.html
Copyright © 2011-2022 走看看