【问题标题】:Getting parseerror on my ajax result return在我的 ajax 结果返回上获取 parseerror
【发布时间】:2016-04-24 18:58:44
【问题描述】:

我不确定为什么会出现解析错误。我在我的 ajax 上动态设置 dataType,当我使用 json 作为 dataType 调用它时,我得到一个解析错误。

MVC 控制器动作

    public ProductViewModel UpdateProduct(ProductViewModel product)
    {
        var productContract = Mapper.Map<ProductViewModel, ProductContract>(product);
        var productReturned = _productService.UpdateProduct(productContract);

        if (productReturned.HasValue)
        {
            return Mapper.Map<ProductContract, ProductViewModel>(productReturned.Value);
        }
        return null;
    }

Ajax 调用

var ajaxCall = function (destinationUrl, dataToPost, ajaxDataType, element, callbackFunction) {
    $.ajax({
        url: destinationUrl,
        data: dataToPost,
        contentType: "application/json",
        dataType: ajaxDataType,
        success: function (data) {
            callbackFunction(data, element);
        },
        error: function (req, status, errorObj) {
            console.log(status);
        }
    });
}

回调函数

这是在 ajax 成功时运行的方法,我的数据库已成功更新,但我需要返回的数据来更新 UI。我试着像datadata.ddata.d[0]一样得到它

function updateProductRow(data, element) {
    console.log(data.d[0]);
}

【问题讨论】:

  • 您是否在开发者工具中检查了返回数据?
  • @KarthikMR 这就是为什么我要记录返回的数据,它的解析错误
  • 这意味着您没有返回有效的 json。 return null 肯定会导致这种情况。我不熟悉其他返回案例中的代码,那是生成 json 吗?看起来不像
  • @DelightedD0D 嘿,感谢您的回复,我发送的数据是有效的,因此它没有命中代码的 return null 部分,而是返回一个对象。
  • 嗯,我不确定您对dataType 的理解是否正确。根据文档。 "dataType (default: Intelligent Guess (xml, json, script, or html)) Type: String, 你期望从服务器返回的数据类型。” 你直接返回一个对象,您可能需要先将其转换为 JSON。也许通过使用一些序列化功能,但我不熟悉 asp 但这个看起来很正确stackoverflow.com/questions/6201529/…

标签: jquery json ajax asp.net-mvc parse-error


【解决方案1】:

我想通了,对于带有控制器操作的 ASP.NET MVC 应用程序,我只需要在我的方法上方有一个属性来接受将成为帖子的动词。并且还将返回类型转换为 JSON 结果。

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult UpdateProduct(ProductViewModel product)
    {
        var productContract = Mapper.Map<ProductViewModel, ProductContract>(product);
        var productReturned = _productService.UpdateProduct(productContract);

        if (productReturned.HasValue)
        {
            return Json(Mapper.Map<ProductContract, ProductViewModel>(productReturned.Value));
        }
        return null;
    }

【讨论】:

  • 作为观察,如果您有 return null;,您可能会考虑返回一个有效的 JSON 响应,其中包含有意义的错误消息而不是 null。目前,如果您曾经点击过return null;,您将得到与您询问的相同的解析错误。相反,返回有意义的错误消息会更优雅,并将帮助您提供更好的整体用户体验。只是我的两美分:)
  • @DelightedD0D 谢谢!...我计划返回类似 {description: "an error has occurred"}.. 你有电子邮件吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-08
  • 2018-03-19
  • 1970-01-01
  • 2012-02-09
  • 2016-07-03
  • 1970-01-01
相关资源
最近更新 更多