文章内容

C# mvc jquery.form.js和jquery.validator.js冲突的解决方法

  • 2018-08-11 20:19:30
  • 244
  • 0
  • 0

开发项目时,需要用到ajax上传图片。由于本人不打算使用上传插件来上传图片,所以这里就需要使用jquery.form.js的ajaxSubmit方法来提交

input file。

问题来了,由于在需要上传的 

 <input type="file" class="hidden" name="imgfile" accept="image/*" id="file" />

外围嵌套了一层form表单,并且该表单引用了jquery.validator.js来验证字段。

<form class="form-horizontal navtabform" id="file-form" enctype="multipart/form-data" method="post"
 data-validator-option='{stopOnError:false, timely:1, theme:"yellow_right"}' 
 style="margin-top:20px;"  action="/Default/changepwd_post">
    <div class="form-group">
        <label class="col-sm-1 text-left control-label">帐号</label>
        <div class="col-sm-3">
            <input class="form-control" name="userid" readonly="readonly" type="text" value="">
        </div>
    </div>
    <div class="form-group">
        <label class="col-sm-1 text-left control-label">姓名</label>
        <div class="col-sm-3">
            <input class="form-control" name="username" data-rule="姓名: required;" type="text" value="" placeholder="请输入姓名">
        </div>
    </div>
    <div class="form-group">
        <label class="col-sm-1  text-left control-label">头像</label>
        <div class="col-sm-3">
            <img src="~/Public/themes/img/003.png" id="headerimg" />
            <input type="file" class="hidden" name="imgfile" accept="image/*" id="file" />
            <button type="button" id="filebtn" class="col-sm-3 btn btn-primary">选择</button>
        </div>
    </div>
    <br />
    <div class="form-group">
        <label class="col-sm-1  text-left control-label"></label>
        <div class="col-sm-3">
            <button type="submit" class="col-sm-3 btn btn-primary">保存</button>
        </div>
    </div>
</form>
<script>
    $("#filebtn").on("click", function (e) {
        //阻止冒泡
        e.stopPropagation();
        $("#file").trigger("click");
        $("#file").on("change", function (e) {
            //阻止冒泡
            e.stopPropagation();

            $(this).off("change");

            //普通ajax无法提交file,需要借助jquery.form.js 里面的ajaxSubmit
            //首先声明提交参数
            var options =
            {
                type: "post",
                url: "/public/upload?t=img",
                async: false,
                cache: true,
                success: function () {
                    try {
                        json = JSON.parse(json);
                        switch (json.code) {
                            case "200":
                                toastr.success(json.message);
                                break;
                            case "202":
                                //显示
                                toastr.success(json.message);
                                var i = window.setTimeout(function () {
                                    window.clearTimeout(i);
                                    //隐藏
                                    $("#loadingModal").modal('hide');
                                    window.location.href = json.url;
                                }, 800)
                                break;
                            case "300":
                                toastr.error(json.message);
                                break;
                            default:
                                toastr.error("返回JSON格式错误!");
                                break;
                        }
                    } catch (e) {
                        toastr.error("错误:" + json);
                    }
                },
                error: function (e) {
                    toastr.error("错误:" + e.responseText);
                }
            }
            //调用ajaxSubmit
            $("#file-form").ajaxSubmit(options);
        })
    });
</script>

image.png

这个时候执行代码点击选择,发现ajaxSubmit根本没有触发后台的方法。

这个时候百度了一下,发现了网上有人遇到过两个js冲突的问题

https://www.cnblogs.com/jackluo/archive/2013/03/26/2981845.html

由于本人环境和上述链接不一样,所以没办法按照上诉方法解决问题,

这个时候突发奇想,是不是可以自己通过jqeury来创建表单。将这个表单提交呢?

尝试后发现的确能将input file上传上去,并且后台代码也能够获取到该input file。

但是检查html内容发现多了一个表单出来,这个时候就需要在表单提交后移除掉。

具体代码如下:

<form class="form-horizontal navtabform"  enctype="multipart/form-data" method="post" 
data-validator-option='{stopOnError:false, timely:1, theme:"yellow_right"}'
 style="margin-top:20px;"  action="/Default/changepwd_post">
    <div class="form-group">
        <label class="col-sm-1 text-left control-label">帐号</label>
        <div class="col-sm-3">
            <input class="form-control" name="userid" readonly="readonly" type="text" value="">
        </div>
    </div>
    <div class="form-group">
        <label class="col-sm-1 text-left control-label">姓名</label>
        <div class="col-sm-3">
            <input class="form-control" name="username" data-rule="姓名: required;" 
            type="text" value="" placeholder="请输入姓名">
        </div>
    </div>
    <div class="form-group">
        <label class="col-sm-1  text-left control-label">头像</label>
        <div class="col-sm-3">
            <img src="~/Public/themes/img/003.png" id="headerimg" />
            <input type="file" class="hidden" name="imgfile" accept="image/*" id="file" />
            <button type="button" id="filebtn" class="col-sm-3 btn btn-primary">选择</button>
        </div>
    </div>
    <br />
    <div class="form-group">
        <label class="col-sm-1  text-left control-label"></label>
        <div class="col-sm-3">
            <button type="submit" class="col-sm-3 btn btn-primary">保存</button>
        </div>
    </div>
</form>
<script>
   $("#filebtn").on("click", function (e) {
        //阻止冒泡
        e.stopPropagation();
        var _this = $(this);
        $("#file").trigger("click");
        $(document).on("change", "#file", function (e) {
            //阻止冒泡
            e.stopPropagation();
            console.info(1);
            $(document).off("change", "#file")
            var form = $("<form method='post'></form>");
            var inputfile = $("#file");
            form.append(inputfile);
            form.appendTo("body");
            form.css('display', 'none');
            //普通ajax无法提交file,需要借助jquery.form.js 里面的ajaxSubmit
            //首先声明提交参数
            var options =
            {
                type: "post",
                url: "/public/uploadFile?t=img",
                async: false,
                cache: true,
                success: function (json) {
                    try {
                        json = JSON.parse(json);
                        switch (json.code) {
                            case "200":
                                $("#headerimg").attr("src", json.message);
                                break;
                            case "300":
                                toastr.error(json.message);
                                break;
                            default:
                                toastr.error("返回JSON格式错误!");
                                break;
                        }
                    } catch (e) {
                        toastr.error("错误:" + json);
                    }
                },
                error: function (e) {
                    toastr.error("错误:" + e.responseText);
                }, complete: function () {
                    form.remove();
                    _this.after(inputfile);
                }
            }
            //调用ajaxSubmit
            $(form).ajaxSubmit(options);
        });
    });
</script>

OK,成功解决问题!

虽然说解决方法不完美,但是同样解决了纠结许久的问题(不管黑猫白猫,抓到耗子就是好猫~~~~~)。

如果路过的大神有更完美的解决方法,麻烦评论指导下,谢谢~~