Django+Ajax+jQuery实现网页动态更新

views.py中的修改


增加相应的请求处理函数:


def getdevjson(request):
    print 'get here'
    if ('key' in request.GET):
        searchkey = request.GET.get('key')
        return JsonResponse(search(searchkey))
    else:
        return HttpResponse('Sorry!')

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Django实现进度条,可以使用Django框架提供的HttpResponse对象和Ajax技术。 首先,在views.py中编写一个函数,用于处理上传文件的请求。该函数可以使用Python的os模块来执行上传文件的操作,并在上传过程中输出进度信息。 然后,在该函数中使用Django的HttpResponse对象来返回上传进度信息。可以将进度信息转化为JSON格式,并使用HttpResponse对象的content_type参数来指定返回的数据类型。 最后,在前端使用Ajax技术来获取HttpResponse对象中的进度信息,并将其显示在进度条上。 下面是一个简单的示例代码: ```python # views.py import os from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt import json @csrf_exempt def upload(request): if request.method == 'POST': file = request.FILES.get('file') file_path = '/path/to/upload/directory/' + file.name with open(file_path, 'wb+') as f: for chunk in file.chunks(): f.write(chunk) uploaded_size = f.tell() total_size = file.size progress = uploaded_size / total_size response_data = { 'progress': progress, 'uploaded_size': uploaded_size, 'total_size': total_size } response_json = json.dumps(response_data) response = HttpResponse(response_json, content_type='application/json') response['Content-Length'] = len(response_json) yield response # upload.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Upload File</title> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> </head> <body> <form id="upload-form" method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="file"> <button type="submit">Upload</button> </form> <div> <progress id="progress-bar" value="0" max="1"></progress> <span id="progress-text">0%</span> </div> <script type="text/javascript"> $(document).ready(function() { $('#upload-form').submit(function(event) { event.preventDefault(); var formData = new FormData(this); $.ajax({ url: '/upload/', type: 'POST', data: formData, processData: false, contentType: false, xhr: function() { var xhr = new window.XMLHttpRequest(); xhr.upload.addEventListener('progress', function(event) { if (event.lengthComputable) { var percentComplete = event.loaded / event.total; $('#progress-bar').val(percentComplete); $('#progress-text').text(percentComplete * 100 + '%'); } }, false); return xhr; }, success: function(response) { console.log('Upload complete!'); }, }); }); }); </script> </body> </html> ``` 在这个例子中,upload函数会处理上传文件的请求,并在上传过程中输出进度信息。在前端,使用Ajax技术来获取HttpResponse对象中的进度信息,并将其显示在进度条上。 通过访问http://yourdomain.com/upload/即可上传文件并动态显示进度条。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值