上传文件
a. Form表单上传,页面刷新(基本不用这种方式)
b. Ajax方式:
$(function () { $(‘#btn1‘).click(function () { var fm = new FormData(); fm.append(‘fffff‘, document.getElementById(‘ggggg‘).files[0]); fm.append(‘usernmae‘,‘root‘); $.ajax({ url: "/ajax-upload/", type: ‘POST‘, data: fm, processData: false, // tell jQuery not to process the data contentType: false, // tell jQuery not to set contentType success:function (arg) { console.log(arg); } }) }) })
目前兼容游览器不够完善
c. "伪"Ajax操作 ,目前最主流
1. iframe + Form表单
2. iframe onload
3. $(‘#ifr‘).contents().
4. 上传按钮透明度
<form id="id_publish_form" action="/publish/" method="POST" enctype="multipart/form-data" target="ifr"> {% csrf_token %} {{ publish_form.title }} <span class="label label-warning" id="id_alert_titile"></span><br> {{ publish_form.summary }} <span class="label label-warning" id="id_alert_summary"></span><br> <input type="file" class="form-control" name="picture_file" id="id_picture_file"> <span class="label label-warning" id="id_alert_file"></span><br> {{ publish_form.nt_id }} <span class="label label-warning" id="id_alert_nt_id"></span><br> </form> {#onload 事件会在页面或图像加载完成后立即发生#} <iframe id="ifr" name="ifr" onload="successBack();" style="display: none"></iframe>
js部分:
//onload 执行的回调函数 function successBack() { var v = $(‘#ifr‘).contents().find(‘body‘).html(); var obj = JSON.parse(v); if (obj.status) { location.href = ‘/‘; } else { if (obj.error) { $(‘#id_alert_file‘).text(obj.error); } else { $(‘#id_alert_titile‘).text(obj.data.title); $(‘#id_alert_summary‘).text(obj.data.summary); $(‘#id_alert_nt_id‘).text(obj.data.nt_id); } } }
预览图片:
如果需要预览图片文件时,后端返回文件路径,js生成一个<img>
时间: 2024-11-05 22:55:53