ajax总结

JQUERY AJAX例子(数据,文件上传)

2017-07-28  本文已影响0人  赖三石

urls.py

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

template-ajax_jquery_test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<input type="text" id="a1">
<input type="file" id="a2">
<input type="button" value="点击" onclick="ajax_jquery_test()">
</body>
<script src="/static/jquery.js"></script>
<script type="text/javascript">

    function ajax_jquery_test(){

        var text = $('#a1').val();
        //var fileobj = document.getElementById('a2').files[0];
        var fileobj = $('#a2')[0].files[0];
        var fd = new FormData();
        fd.append('user', text);
        fd.append('obj', fileobj);

        $.ajax({
            type:'POST',
            url:'/ajax_jquery_test/',
            data:fd,
            processData:false,  // 告诉jquery不转换数据
            contentType:false,  // 告诉jquery不设置内容格式
            success:function(res,a1,a2){
                console.log(res);
            }
        })

    }
</script>
</html>

views.py

def test(request):
    return render(request, 'ajax_jquery_test.html')


def ajax_jquery_test(request):
    res = {'status': True, 'data': 'ok'}
    user = request.POST.get('user')
    obj = request.FILES.get('obj')

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

    import json
    return HttpResponse(json.dumps(res))
上一篇 下一篇

猜你喜欢

热点阅读