5分钟学会ajax方式提交Form表单及文件上传

                                        Ajax方式提交Form表单及文件上传

一、前言

       利用 Ajax方式提交 Form表单及文件上传。

       在此记录下,分享给大家。

 二、代码如下

-- html代码


    <form id="yysForm" method="post" action="/yys/batch/upload" enctype="multipart/form-data">
        <em>导入数据</em>
        <p>
            <input type="text" id="showUpload"/><span>浏览</span>
            <input type="file" name="upload" id="upload" accept="application/vnd.ms-excel" οnchange="javascript:checkImportFile()"/>
        </p>
        <input id="btn_uoload" type="button" value="开始导入"/>
        <input id="btn_uoloading" type="button" value="正在导入..." style="display:none;"/>
    </form>
-- js代码


var yysFlag = true; //防止按钮重复点击

$(function(){
    $("#btn_uoload").click(function() {

        if(!$("#upload").val()){
            $.MsgBox.Alert("温馨提示", "请选择上传文件");
            return false;
        }

        if(yysFlag){
            yysFlag = false;
            $("#btn_uoload").hide();
            $("#btn_uoloading").show();
			
            /**
             * 使用ajax的文件上传
             */
            fileUpload("yysForm", "yysMethod");
        }
		
    });
})


/**
 * ajax文件上传
 * @param formId 文件上传表单ID
 * @param methodName 回调函数:文件上传成功后需要执行的方法
 */
function fileUpload(formId, methodName){
    $.ajax({
        type : "POST",
        url : $("#"+formId).attr("action"),
        data : new FormData($("#"+formId)[0]),
        dataType: 'json',
        cache: false, // 禁止文件缓存
        processData: false, // 通过data选项传递进来的数据,如果是一个对象(技术上讲只要不是字符串),都会处理转化成一个查询字符串,以配合默认内容类型 "application/x-www-form-urlencoded"。如果要发送 DOM 树信息或其它不希望转换的信息(eg:对象),请设置为 false。
        contentType: false, // 避免 JQuery 对其操作,从而失去分界符,而使服务器不能正常解析文件
        async:true, //异步
        success : function(result) {
            if(result.success){
                // 执行上传成功后的逻辑
                eval(methodName)(result.result);
            }else{
                // 请求上传文件结果页
                window.location.href = result.message;
            }
        },
        error : function (e) {
            window.location.href = "/error/" + e.status;
        }
    });
}


/**
 * 回调函数
 */
function yysMethod(result){

    // ...业务逻辑(eg:百分比遮罩层)...

}

                       Now ~ ~ ~写到这里,就写完了,如果有幸帮助到你,请记得关注我,共同一起见证我们的成长

发布了74 篇原创文章 · 获赞 253 · 访问量 13万+

猜你喜欢

转载自blog.csdn.net/qq_42175986/article/details/87630704