Ajax



一。

.py

from django.shortcuts import render,HttpResponse

# Create your views here.
def index(request):
    return render(request,'index.html')

def ajax(request):
    import json
    print(request.POST)
    print(request.body)
    result={'status':True,'message':'lalalal'}
    return HttpResponse(json.dumps(result))

.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="/static/jquery-3.3.1.js"></script>
</head>
<body>
<h1>Ajax全套</h1>
<h3>jequery ajax</h3>
<input type="button" value="jequery ajax" id="btn1"><br/>

<h3>原生 ajax</h3>
<input type="button" value="原生 ajax" id="btn2"><br/>

<h3>Iframe+form表单实现伪Ajax</h3>
<iframe id="iframe01" method='post' name="ifram"></iframe>
<form action="/ajax3/" target="ifram" id="form01">
    <input type="text" name="root" value="111">
    <input type="button" value="伪Ajax" id="btn3">
</form>
</body>
</html>
<script>
    $('#btn1').click(function () {
        $.ajax({
            url: '/ajax1/',
            type: 'POST',
            data: {'data': 'hello'},
            success: function (arg) {
                console.log(arg)
            }
        });
    });

    document.getElementById('btn2').οnclick=function () {
        var xlh = new XMLHttpRequest();
        xlh.onreadystatechange = function () {
            if (xlh.readyState == 4) {
                //接收完毕服务器返回的数据
                console.log(xlh.responseText);
            }
        };
        xlh.open('POST', '/ajax2/');
        xlh.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');//GET请求不需要加
        xlh.send('p=123');
    };


    document.getElementById('btn3').onclick = function () {
        document.getElementById('form01').submit();
        document.getElementById('iframe01').onload = function () {
            var str = this.contentWindow.document.body.innerHTML;
            var obj = JSON.parse(str);
            if (obj.status) {
                alert(obj.message)
            }

        }
    }
</script>

二。Ajax上传

.py

from django.shortcuts import render,HttpResponse

# Create your views here.
def index(request):
    return render(request,'index.html')

def ajax(request):
    import json
    print(request.GET)
    print(request.POST)
    print(request.FILES)
    result={'status':True,'message':'lalalal'}
    return HttpResponse(json.dumps(result))
.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="/static/jquery-3.3.1.js"></script>
</head>
<body>
<h1>Ajax全套</h1>
<div>
    <h3>1.jequery ajax</h3>
    <input type="button" value="jequery ajax" id="btn1">
</div>
<div>
    <h3>2.原生 ajax</h3>
    <input type="button" value="原生 ajax" id="btn2">
</div>
<div>
    <h3>3.Iframe+form表单实现伪Ajax</h3>
    <iframe id="iframe01" name="ifram"></iframe>
    <form action="/ajax3/" target="ifram" id="form01">
        <input type="text" name="root" value="111">
        <input type="button" value="伪Ajax" id="btn3">
    </form>
</div>
<div>
    <h3>4.Ajax文件上传</h3>
    <input type="file" id="img">
    <input type="button" value="4.1ajax上传文件" id="btn4">
    <input type="button" value="4.2原生ajax上传文件" id="btn5">
</div>
<div>
    <h3>4.3Iframe+form表单实现伪Ajax上传文件</h3>
    <iframe id="iframe02" name="ifram02" style="display: none;"></iframe>
    <form action="/ajax6/" target="ifram02" id="form02" enctype="multipart/form-data" method="post">
        <input type="text" name="k1" value="v1">
        <input type="file" name="k2" >
        <input type="button" value="4.3Iframe+form表单实现伪Ajax上传文件" id="btn6">
    </form>
</div>
</body>
</html>
<script>
    //1.jequery ajax
    $('#btn1').click(function () {
        $.ajax({
            url: '/ajax1/',
            type: 'POST',
            data: {'data': 'hello'},
            success: function (arg) {
                console.log(arg)
            }
        });
    });
    //2.原生 ajax
    document.getElementById('btn2').onclick = function () {
        var xlh = new XMLHttpRequest();
        xlh.onreadystatechange = function () {
            if (xlh.readyState == 4) {
                //接收完毕服务器返回的数据
                console.log(xlh.responseText);
            }
        };
        xlh.open('POST', '/ajax2/');
        xlh.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');//GET请求不需要加
        xlh.send('p=123');
    };
    //3.Iframe+form表单实现伪Ajax
    document.getElementById('btn3').onclick = function () {
        document.getElementById('form01').submit();
        document.getElementById('iframe01').onload = function () {
            var str = this.contentWindow.document.body.innerHTML;
            var obj = JSON.parse(str);
            if (obj.status) {
                alert(obj.message)
            }

        }
    };

    //1. ajax上传文件
    $('#btn4').click(function () {
        var data = new FormData();//FormData可以包裹数据;数据可以是文件
        data.append('k1', 'v1');
        var file01 = document.getElementById('img').files[0];
        data.append('k2', file01);

        $.ajax({
            url: '/ajax4/',
            type: 'POST',
            data: data,
            success: function (arg) {
                console.log(arg)
            },
            contentType: false,
            processData: false
        })
    });
    //2.原生ajax上传文件
    document.getElementById('btn5').onclick = function () {
         var data = new FormData();
        data.append('k1', 'v1');
        var file01 = document.getElementById('img').files[0];
         data.append('k2', file01);

        var xlh = new XMLHttpRequest();
        xlh.onreadystatechange = function () {
            if (xlh.readyState == 4) {
                //接收完毕服务器返回的数据
                console.log(xlh.responseText);
            }
        };
        xlh.open('POST', '/ajax5/');
        xlh.send(data);
    };
    //3.Iframe+form表单实现伪Ajax上传文件
    document.getElementById('btn6').onclick = function () {
        document.getElementById('form02').submit();
        document.getElementById('iframe02').onload = function () {
            var str = this.contentWindow.document.body.innerHTML;
            var obj = JSON.parse(str);
            if (obj.status) {
                alert(obj.message)
            }

        }
    };
</script>

模仿抽屉做图片上传(Iframe+form表单实现伪Ajax上传文件

.py

from django.shortcuts import render,HttpResponse

# Create your views here.


def uploadFile(request):
    import json
    import os
    if request.method=='GET':
        return render(request,'index2.html')
    if request.method=='POST':
        result = {'status': True, 'data': None}
        req=request.FILES.get('k2')
        file_path=os.path.join('static',req.name)
        f=open(file_path,'wb')
        for i in req.chunks():
            f.write(i)
        f.close()
        result['data']=file_path
        return HttpResponse(json.dumps(result))

.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="/static/jquery-3.3.1.js"></script>
</head>
<body>
<div>
    <h3>4.3Iframe+form表单实现伪Ajax上传文件(模拟抽屉)</h3>
    <iframe id="iframe02" name="ifram02" style="display: none;"></iframe>
    <form action="/uploadFile/" target="ifram02" id="form02" enctype="multipart/form-data" method="post">
        <input type="file" name="k2" οnchange="uploadFile();" >
    </form>
</div>
<div id="preview">

</div>
</body>
</html>

<script>

   function uploadFile() {
        document.getElementById('form02').submit();
        document.getElementById('iframe02').onload = function () {
            var str = this.contentWindow.document.body.innerHTML;
            var obj = JSON.parse(str);
            if (obj.status) {
                var img=document.createElement('img');
                console.log(obj.data);
                img.src='/'+obj.data;//没搞懂为什么加‘/’,视频里没有加

                $('#preview').empty().append(img);
            }
        }
    };
</script>



.py

def jsonp(request):
    return render(request,'jsonp.html')

.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
        <script src="/static/jquery-3.3.1.js"></script>
</head>
<body>
<input type="button" value="发送" οnclick="jsonp();">
</body>
</html>
<script>
    function jsonp() {
        $.ajax({
            url:'http://www.jxntv.cn/data/jmd-jxtv2.html',
            type:'GET',//只能发GET,写POST无效
            dataType:'jsonp',
            jsonp:'callback',
            jsonpCallback:'list'//期待返回包裹的函数名字符串为list,可以任意该,但有的网站不专业,给写死了

        })
    }
    function list(arg) {
        console.log(arg)
    }
</script>





























































  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值