时间:2021-07-01 10:21:17 帮助过:4人阅读
最近在做项目时,遇到上传图片需求,且在不跳转的情况下获取到返回信息
1. 使用ajax发送异步请求,经多次测试,最终以失败告终
2. iframe 禁止跳转(未尝试)
3. 修改form标签内提交请求逻辑
1. html代码:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no"> 6 <meta name="apple-mobile-web-app-capable" content="yes"> 7 <meta name="apple-mobile-web-app-status-bar-style" content="black"> 8 <meta name="format-detection" content="telephone=no"> 9 <meta http-equiv="Expires" content="-1"> 10 <meta http-equiv="Cache-Control" content="no-cache"> 11 <meta http-equiv="Pragma" content="no-cache"> 12 <title>上传赛事气象新闻</title> 13 <link rel="stylesheet" href="css/uploadnews.css?1.1.11"> 14 <script src="js/rem.js?1.1.11"></script> 15 </head> 16 <body> 17 <p class="upload"> 18 <h1>上传赛事气象新闻</h1> 19 <p class="content"> 20 <p class="label">标题:</p> 21 <input type="text" name="title" id="title"> 22 <p class="label">内容:</p> 23 <textarea id="detail"></textarea> 24 <p class="label">图片:</p> 25 <form class="fupload" method="POST" action="http://tianjinqixiang.tianqi.cn:8080/tjqyh/testUploadFiles" enctype="multipart/form-data" > 26 <input type="submit" value="上传" class="upload_button"> 27 <br> 28 <input type="file" name="file" value="选择图片" class="choose_img"> 29 <br> 30 <input type="file" name="file" value="选择图片" class="choose_img"> 31 <br> 32 <input type="file" name="file" value="选择图片" class="choose_img"> 33 <br> 34 <input type="file" name="file" value="选择图片" class="choose_img"> 35 </form> 36 <input type="button" value="提交" id="upButton"> 37 </p> 38 </p> 39 </body> 40 </html> 41 <script src="js/jquery-1.10.1.min.js?1.1.11"></script> 42 <script> 43 var imgURL = ''; 44 // 表单提交不进行跳转获取返回数据 45 $('form').submit(function (event) { 46 event.preventDefault(); 47 var form = $(this); 48 if (!form.hasClass('fupload')) { 49 //普通表单 50 $.ajax({ 51 type: form.attr('method'), 52 url: form.attr('action'), 53 data: form.serialize() 54 }).success(function () { 55 56 }).fail(function (jqXHR, textStatus, errorThrown) { 57 //错误信息 58 }); 59 } 60 else { 61 // mulitipart form,如文件上传类 62 var formData = new FormData(this); 63 $.ajax({ 64 type: form.attr('method'), 65 url: form.attr('action'), 66 data: formData, 67 mimeType: "multipart/form-data", 68 contentType: false, 69 cache: false, 70 processData: false 71 }).success(function (yy) { 72 alert('上传成功') 73 imgURL = yy 74 }).fail(function (jqXHR, textStatus, errorThrown) { 75 //错误信息 76 }); 77 }; 78 }); 79 $("#upButton").click(function(){ 80 upMessage(imgURL) 81 }) 82 function upMessage(imgdata){ 83 var title = $('#title').val() 84 var content = $('#detail').val() 85 window.location.href='./userInfo/newseditor?title='+title+'&content='+content+'&sitepng='+imgdata 86 } 87 // http://127.0.0.1:8080/userInfo/newseditor?title=气象新闻测试周刊&content=今天晴转龙卷风&sitepng=/home/wangxinyu/news/11B01_red.png88 </script>
View Code
2. 其他样式文件此处不做概述。
以上就是form表单提交图片遇到的问题分析的详细内容,更多请关注Gxl网其它相关文章!