【问题标题】:Error "Requested JSON parse failed" in downloading excel file下载 Excel 文件时出现“请求的 JSON 解析失败”错误
【发布时间】:2017-10-20 07:22:42
【问题描述】:

我有一个操作方法,它返回一个 excel 文件作为回报。我正在使用 ajax 调用该操作方法。我收到Requested JSON parse failed

 $.ajax({
            url: importUrl,
            data: {
                X: "12",
                Y: "12",
                Z: "12"
            },
            success: function (data) {
                alert("S: "+data);
            },
            error: function (jqXHR, exception) {
                var msg = '';
                if (jqXHR.status === 0) {
                    msg = 'Not connect.\n Verify Network.';
                } else if (jqXHR.status == 404) {
                    msg = 'Requested page not found. [404]';
                } else if (jqXHR.status == 500) {
                    msg = 'Internal Server Error [500].';
                } else if (exception === 'parsererror') {
                    msg = 'Requested JSON parse failed.';
                } else if (exception === 'timeout') {
                    msg = 'Time out error.';
                } else if (exception === 'abort') {
                    msg = 'Ajax request aborted.';
                } else {
                    msg = 'Uncaught Error.\n' + jqXHR.responseText;
                }
                console.log(msg);
            }
        });



public ActionResult ExportReportToExcel(string X, string Y, string Z)
        {
            if (HttpContext.Request.UrlReferrer == null)
                TempData["PDFPrevUrl"] = Url.RouteUrl("PageNotFound");
            else if (TempData["PDFPrevUrl"] == null)
                TempData["PDFPrevUrl"] = HttpContext.Request.UrlReferrer.PathAndQuery;

            var customer = _authenticationService.CurrentCustomer;
            if (customer == null)
                return new LmsHttpUnauthorizedResult();

            string filename = "Report";
            try
            {
                XLWorkbook wb = new XLWorkbook(Server.MapPath(@"~/Content/CumulativePerformanceReportTemplate.xlsx"));
                XElement userprogress = XElement.Load(Server.MapPath(@"~/Content/Export.xml")).Element("cumulativeperformancereport");
                int datarow = int.Parse(userprogress.Element("T").Attribute("row").Value.Trim());
                int datacol = int.Parse(userprogress.Element("T").Attribute("col").Value.Trim());
                IXLWorksheet WS = wb.Worksheet(1);
                WS.Cell(datarow, datacol).Value = customer.Name;
                datarow = int.Parse(userprogress.Element("X").Attribute("row").Value.Trim());
                datacol = int.Parse(userprogress.Element("X").Attribute("col").Value.Trim());
                WS.Cell(datarow, datacol).Value = X;
                datarow = int.Parse(userprogress.Element("Y").Attribute("row").Value.Trim());
                datacol = int.Parse(userprogress.Element("Y").Attribute("col").Value.Trim());
                WS.Cell(datarow, datacol).Value = Y;
                datarow = int.Parse(userprogress.Element("Z").Attribute("row").Value.Trim());
                datacol = int.Parse(userprogress.Element("Z").Attribute("col").Value.Trim());
                WS.Cell(datarow, datacol).Value = Z;
                Response.Clear();
                Response.Buffer = true;
                Response.Charset = "";
                Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                Response.AddHeader("content-disposition", "attachment;filename=" + filename + "_Summary.xlsx");
                using (MemoryStream MyMemoryStream = new MemoryStream())
                {
                    wb.SaveAs(MyMemoryStream);
                    MyMemoryStream.WriteTo(Response.OutputStream);
                    Response.Flush();
                    Response.End();

                }
                return null;
            }

            catch (Exception ex)
            {
                return Redirect(TempData["PDFPrevUrl"].ToString());
            }

        }

为什么会出现这个错误?

【问题讨论】:

  • 你确定控制器动作应该return null吗? X 在此处的 data 参数处也​​声明了两次,这可能导致解析错误:data: { X: "12", Y: "12", X: "12" },
  • @Tetsuya Yamamoto 那是排版。我做了一些更正。是的,我确信控制器操作应该返回 null。

标签: c# json ajax excel


【解决方案1】:

为什么要使用后端来创建一个 excel 文件然后下载它......它的过度杀伤和下载部分是困难的

在客户端使用像 Javascript 这样的轻量级...它将从 XML 创建 excel 并使用 download 下载它 属性...

    var data_type = 'data:application/vnd.ms-excel';
    var table_div = document.getElementById('table_wrapper');
    var table_html = table_div.outerHTML.replace(/ /g, '%20');

Here is Solution

【讨论】:

    【解决方案2】:

    发送文件时可能是服务器端错误。 您是否尝试将响应 Content Type 更改为 application/vnd.ms-excel


    我向你展示了一个最小的工作示例

    // Server side
    public ActionResult GimmeFile()
    {
        var bytes = System.IO.File.ReadAllBytes(@"path_to_your_file.xlsx");
        return File(bytes, "application/vnd.ms-excel", "Myfile.xls");
    }
    

    Ajax 调用的客户端

    $.ajax({
        method: 'POST',
        url: '/Home/GimmeFile',
        success: function (data) {
            alert("S: " + data)
        },
        error: function (jqXHR, ex) {
            console.log(ex)
        }
    })
    

    不管怎样,我不知道你需要在ajax调用后对excel文件做什么, 但如果您需要将其保存到本地,那么您应该改用 HTML5 < a download>

    【讨论】:

    • 如何下载我们得到的这些数据
    • 由于 javascript 安全限制,没有简单的方法可以将文件从网页保存到文件系统 - 您可以将文件保存到浏览器的 local storage - 或查看此 library 或者您可以使用 HTML 标签我之前提到的
    • 我想下载这个文件。那么使用这个有什么意义呢。
    • 你有触发ajax调用的按钮吗?如果是这样,您可以使用&lt;a download href="/Controller/ExportReportToExcel?X=10&amp;Y=20&amp;Z=10" class="btn btn-default"&gt;Download&lt;/a&gt;
    【解决方案3】:

    请求的 JSON 解析失败”表示 AJAX 调用期望获取 JSON 数据作为返回值,但控制器操作方法返回的数据类型不是 JSON 对象。

    通过查看控制器流程并省略一些不相关的代码,您将得到:

    public ActionResult ExportReportToExcel(string X, string Y, string Z)
    {
        // other stuff
    
        var customer = _authenticationService.CurrentCustomer;
        if (customer == null)
            return new LmsHttpUnauthorizedResult();
    
        try
        {   
            // other stuff
    
            return null; // this returns null value instead of expected JSON
        }
    
        catch (Exception ex)
        {
            return Redirect(TempData["PDFPrevUrl"].ToString());
        }
    
    } 
    

    默认情况下,jQuery 尝试根据响应的 MIME 类型(xml、json、脚本或 html,最近的默认值为 JSON)推断 dataType 参数。因此,您需要通过以下这些方法return a JSON object

    // ContentResult
    return Content("message_text", "application/json");
    
    // JsonResult
    return Json("message_text", JsonRequestBehavior.AllowGet);
    

    如果要通过AJAX返回文件下载,可以使用window.locationwindow.location.href重定向:

    $.ajax({
            url: importUrl, // this should be refer to JsonResult action
            data: {
                X: "12",
                Y: "12",
                Z: "12"
            },
            success: function (data) {
                // deal with data response here
                window.location = downloadUrl; // redirect to FileResult action
            },
            error: function (jqXHR, exception) {
                // other stuff
            }
    }
    
    // example controller to return Excel binary file
    public FileResult DownloadFile(string fileName)
    {
        // other stuff
        byte[] content = TempData["something"] as byte[];
    
        return File(content, "application/vnd.ms-excel", fileName);
    }
    

    注意:上面的解释大多是微不足道的,您当前的实现可能与给定的示例不同。

    类似问题:

    Download Excel file via AJAX MVC

    jQuery returning "parsererror" for ajax request

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-28
      • 2021-09-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多