ajax

概述

对于WEB应用程序:用户浏览器发送请求,服务器接收并处理请求,然后返回结果,往往返回就是字符串(HTML),浏览器将字符串(HTML)渲染并显示浏览器上。

1、传统的Web应用

一个简单操作需要重新加载全局数据

2、AJAX

AJAX,Asynchronous JavaScript and XML (异步的JavaScript和XML),一种创建交互式网页应用的网页开发技术方案。

  • 异步的JavaScript:
    使用 【JavaScript语言】 以及 相关【浏览器提供类库】 的功能向服务端发送请求,当服务端处理完请求之后,【自动执行某个JavaScript的回调函数】。
    PS:以上请求和响应的整个过程是【偷偷】进行的,页面上无任何感知。
  • XML
    XML是一种标记语言,是Ajax在和后台交互时传输数据的格式之一

利用AJAX可以做:
1、注册时,输入用户名自动检测用户是否已经存在。
2、登陆时,提示用户名密码错误
3、删除数据行时,将行ID发送到后台,后台在数据库中删除,数据库删除成功后,在页面DOM中将数据行也删除。

原生ajax上传数据

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <input type="text"/>
    <input type="button" value="ajax1" onclick="ajax1()"/>

    <script>
        function getXHR(){
            var xhr = null;
            if(XMLHttpRequest){
                xhr = new XMLHttpRequest();
            }else{
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }
            return xhr;

        }#兼容
        function ajax1() {
            var xhr = getXHR();
            xhr.open('POST','/ajax_json/');
            xhr.onreadystatechange = function () {
                if(xhr.readyState == 4){
                    //接收完毕
                    console.log(xhr.responseText);
                }
            };
            xhr.setRequestHeader('k1','v1');
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset-UTF-8');
            xhr.send("name=root;pwd=123");

        }
</script>
</body>
</html>

jquery ajax


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="text"/>
<input type="button" value="ajax1" onclick="ajax1()"/>
<script>
function ajax1() {
$.ajax({
'url':'/ajax_json',
'type':'POST',
'data':{'k1':'v1'},
success: function (arg) {
console.log(arg)
}
})

}
</script>
</body>
</html>
 

伪类ajax

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="/ajax_json/" method="POST" target="if1">
        <iframe class="if1" name="if1"></iframe>
        <input type="text" name="username"/>
        <input type="submit" value="提交" onclick="submitForm();"/>
    </form>
    <script>function submitForm() {
            $('#if1').load(function () {
                var text = $('#if1').contents().find('body').text();
                var obj  = JSON.parse(text)
            })
        }
    </script>
</body>
</html>

views.py

def ajax_json(request):
    print(request.POST)
    ret = {'data':request.POST.get('username'),'status':True}
    return HttpResponse(json.dumps(ret))

上传文件

原生ajax(依赖FormData)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<style>
    .upload{
        display: inline-block;
        background-color: aquamarine;
        text-align: center;
        line-height: 50px;
        position: absolute;
        top: 0;
        bottom: 0;
        right: 0;
        left: 0;
        z-index: 90;
    }
    .file{
        width: 100px;height: 50px;opacity: 0;
        position: absolute;
        top: 0;
        bottom: 0;
        right: 0;
        left: 0;
        z-index: 100;
    }
</style>
<body>
    <div style="position: relative; 100px;height: 50px">
        <input class="file" type="file" id="fafafa" name="afafaf"/>
        <a class="upload">上传</a>
    </div>
    <input type="button" value="提交" onclick="xhrSubmit();"/>
    <hr/>

    <script src="/static/jquery-1.12.4.js"></script>
    <script>function xhrSubmit() {
            var file_obj = document.getElementById('fafafa').files[0];
            var fd = new FormData();
            fd.append('fafa',file_obj);
            fd.append('username','root');
            xhr = new XMLHttpRequest();
            xhr.open('POST','/upload_file/');
            xhr.onreadystatechange = function () {
                if(xhr.readyState == 4){
                    //接收完毕
                    console.log(xhr.responseText);
                }
            };
            xhr.send(fd);
        }



    </script>
</body>
</html>

jquery上传文件(依赖FormData)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<style>
    .upload{
        display: inline-block;
        background-color: aquamarine;
        text-align: center;
        line-height: 50px;
        position: absolute;
        top: 0;
        bottom: 0;
        right: 0;
        left: 0;
        z-index: 90;
    }
    .file{
        width: 100px;height: 50px;opacity: 0;
        position: absolute;
        top: 0;
        bottom: 0;
        right: 0;
        left: 0;
        z-index: 100;
    }
</style>
<body>
    <div style="position: relative; 100px;height: 50px">
        <input class="file" type="file" id="fafafa" name="afafaf"/>
        <a class="upload">上传</a>
    </div>
    <input type="button" value="提交2" onclick="jqSubmit();"/>
    <hr/>
    <script src="/static/jquery-1.12.4.js"></script>
    <script>function jqSubmit() {
            var file_obj = document.getElementById('fafafa').files[0];
            var fd = new FormData();
            fd.append('fafa',file_obj);
            fd.append('username','root');
            $.ajax({
                url:'/upload_file/',
                type:'POST',
                data:fd,
                processData:false,
                contentType:false,
                success:function (arg) {
                    console.log(arg)
                }
            })
        }</script>
</body>
</html>

iframe上传文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<style>
    .upload{
        display: inline-block;
        background-color: aquamarine;
        text-align: center;
        line-height: 50px;
        position: absolute;
        top: 0;
        bottom: 0;
        right: 0;
        left: 0;
        z-index: 90;
    }
    .file{
        width: 100px;height: 50px;opacity: 0;
        position: absolute;
        top: 0;
        bottom: 0;
        right: 0;
        left: 0;
        z-index: 100;
    }
</style>
<body>
    <div style="position: relative; 100px;height: 50px">
        <input class="file" type="file" id="fafafa" name="afafaf"/>
        <a class="upload">上传</a>
    </div>
    <form action="/upload_file/" method="POST" enctype="multipart/form-data" target="ifm1">#这里加上target等于ifame的id
        <iframe id="ifm1" name="ifm1"></iframe>
        <input type="file" name="fafa"/>
        <input type="submit" onclick="iframeSubmit();" value="Form提交"/>

    </form>
    <script src="/static/jquery-1.12.4.js"></script>
    <script>
        function iframeSubmit() {
            $('#ifm1').load(function () {
                var text = $('#ifm1').contents().find('body').text();
                var obj = JSON.parse(text);
                console.log(obj);
            })
        }</script>
</body>
</html>

views.py

def upload_file(request):
    username = request.POST.get('username')
    file = request.FILES.get('fafa')
    print(username,file)
    with open(file.name,'wb') as f:
        for line in file.chunks():
            f.write(line)
    return HttpResponse('ok')

JSONP跨域请求(一种请求方式)

由于浏览器具有同源策略,跨域访问时会阻止
解决办法:

  不阻止<script>
  创建script标签
  src=远程地址

注意:

  返回的数据必须是js格式
  只能发GET请求

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <input type="button" onclick="Jsonp();"  value='提交'/>
    <script>
        function Jsonp() {
            var tag = document.createElement('script');
            tag.src = 'http://www.jxntv.cn/data/jmd-jxtv2.html?callback=list&_=1454376870403';#这个API会拿到callback对应的函数名并返回
            document.head.appendChild(tag);
            document.head.removeChild(tag);
        }
        function list(arg) {
            console.log(arg);
        }
    </script>
</body>
</html>

最常用的

    $.ajax({
        url:'http://',
        type:'POST',
        dataType:'jsonp',
        jsonp:'callback',
        jsonpCallback:'list'
    })
原文地址:https://www.cnblogs.com/hongpeng0209/p/6741508.html