伪AJAX例子 - 数据,文件上传(iframe)

urls.py

from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', views.index, name='index'),
    url(r'^iframe_test/', views.iframe_test, name='index'),
]

template-index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <form action="/iframe_test/" method="post" enctype="multipart/form-data" target="ifr">
        <iframe id="ii" name="ifr"></iframe>
        <input type="text" name="u">
        <input type="text" name="p">
        <input type="file" name="fff">
        <input type="submit" value="submit" onclick="click001()">
    </form>
</body>
<script src="/static/jquery.js"></script>
<script>
    function click001(){
        $('#ii').load(function () {
            var text = $('#ii').contents().find('body').text();
            console.log(JSON.parse(text));
        })
    }
</script>
</html>

views.py

from django.shortcuts import render,HttpResponse

# Create your views here.

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


def itest(request):
    u = request.POST.get('u')
    p = request.POST.get('p')
    fileobj = request.FILES.get('fff')
    # print fileobj.chunks(), fileobj.name

    import os
    file_path = os.path.join('static', fileobj.name)
    with open(file_path, 'wb') as f:
        for i in fileobj.chunks():
            f.write(i)

    res = {'u': u, 'p': p}
    import json
    return HttpResponse(json.dumps(res))
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容