Jquery Ajax 要求下载 JSON 文件而不是进入成功块

Jquery Ajax asks to download JSON file instead of going into success block

我正在尝试将 excel 文件上传到 MVC5 中的数据库,这成功了,然后它应该显示已上传的数据。我在一个动作方法中执行这两个动作

public ActionResult UploadExcel(HttpPostedFileBase file)
{
          //logic to upload and get uploaded data into a DataTable "dataLoadedTable"
          ..
          ..
          string JSONresult;
          JSONresult = JsonConvert.SerializeObject(dataLoadedTable);
          return Json(JSONresult, JsonRequestBehavior.AllowGet);
}

然后我尝试使用 jquery ajax 获取此数据,如下所示 -

$("#formId").on("submit", function () {
            $.ajax
                ({
                    url: 'UploadExcel',
                    type:'POST',
                    datatype: 'application/json',
                    contentType: 'application/json; charset=utf-8',
                    success: function (response) {
                        alert(response);
                    },
                    error: function (xhr, status, error) {
                        alert(xhr.responseText);
                        alert(status);
                        alert(error);
                    }
                });

但是在 运行 代码页面要求将数据下载为 json 文件,而不是进入成功块。最初,我认为这是因为数据很大。即使这样也行不通 -

success: function (response) {
  alert("hi");
},

我的 HTML -

@using System.Data
@model DataTable
@{
    ViewBag.Title = "Upload Excel";
    Layout = "~/Views/Shared/_CommonLayout.cshtml";
}


<body>
    @using (Html.BeginForm("UploadExcel", "UploadData", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        <form id="myDataForm">
            <div>
                <h4>Upload Data</h4>
                <div class="card shadow">
                    <div class="p-5">

                        <label>Upload File:</label>
                        <div class="input-group mb-3">
                            <div class="custom-file">
                                <input type="file" name="file" autofocus="autofocus" class="custom-file-input" id="inputGroupFile02" />
                                <label class="custom-file-label" for="inputGroupFile02">Choose file</label>
                            </div>
                            <div class="input-group-append">
                                <button class="btn btn-primary" id="btnUploadData">Upload</button>
                            </div>
                        </div>
                        <script>
                            $('#inputGroupFile02').on('change', function () {
                                //get the file name
                                //var fileName = $(this).val();
                                var fileName = $(this).val().split('\').pop();;
                                //replace the "Choose a file" label
                                $(this).next('.custom-file-label').html(fileName);

                            })
                        </script>

                        <!--Display Error Message-->
                        <div style="color:red;">@ViewBag.Message</div>


                        @if (!string.IsNullOrWhiteSpace(ViewData["Upload Success"] as String))
                        {
                            <div class="alert alert-success alert-dismissible fade show mt-3" role="alert">
                                @Html.ViewData["Upload Success"]
                                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                    <span aria-hidden="true">&times;</span>
                                </button>
                            </div>
                        }


                    </div>
                </div>
            </div>
        </form>
    }
    <table id="dataTable" class="table table-bordered table-striped">
        <thead>
            <tr>
                <th>ABC</th>
                <th>XYZ</th>
                ..
                ..
            </tr>
        </thead>
    </table>
</body>

您需要阻止提交表单。在传递给 submit 处理程序的事件上调用 preventDefault()

$("#formId").on("submit", function(e) {
  e.preventDefault();

  // your ajax here...
});

此外,您似乎没有在 AJAX 请求中发送任何 data?我假设这是在您写出问题时被意外删除的。

此外,顺便说一句,不要使用 alert() 进行调试。它会阻止浏览器并强制数据类型,这是数据一致性时您最不需要的东西。请改用 console.log()console.dir()

看起来问题出在下面的代码上。需要进一步调查原因 -

@using (Html.BeginForm("UploadExcel", "UploadData", FormMethod.Post, new { enctype = "multipart/form-data" }))

我只是将其替换为常规 html 形式,然后添加以下代码以获取 post javascript -

中的文件对象
var $file = document.getElementById('inputGroupFile02'),
                $formData = new FormData();

            if ($file.files.length > 0) {
                for (var i = 0; i < $file.files.length; i++) {
                    $formData.append('file-' + i, $file.files[i]);
                }
            }

并在 ajax 调用中添加了以下内容 -

                data: $formData,
                dataType: 'json',
                contentType: false,
                processData: false,

在控制器中,使用

获取文件对象
                if (Request.Files.Count > 0)
                {
                    foreach (string file in Request.Files)
                    {
                        var _file = Request.Files[file];
                    }
                }

我认为 FormMethod.Post 和 ajax post 可能存在一些冲突。我可能是错的。请随意更正此问题并添加可能的问题。