8

我正在使用以下 Ajax 调用将部分视图加载到 div 中:

  $.ajax({
    url: "/URL",
    type: "POST",
    dataType: "json",
    data: JSON.stringify(request),
    contentType: "application/json; charset=utf-8",
    success: function(data) {
        $('#Result').html(data);
        App.hidePleaseWait();
    },
    error: function (jqXHR, textStatus, errorThrown) {
        App.hidePleaseWait();
        alert(textStatus);
        alert(errorThrown);
    }
});

这是我的控制器:

[HttpPost]
        public ActionResult GetSomething(MyModel formModel)
        {
            var model = new ResultModel();

            try
            {
                model.Data = GetSomeData();
            }
            catch (Exception exception)
            {
                model.ErrorMessage = exception.Message;
            }

            return PartialView("_Results", model);
        }

我收到以下错误"parserrror SyntaxError: Unexpected token <"

似乎 .ajax 调用期望返回 json 而不是 html。我需要做什么来解决这个问题?

谢谢。

4

2 回答 2

31

您需要在 ajax 调用中更改数据类型。

 dataType: "json",

 dataType: "html", 

数据类型告诉类型是 json,但是你发回的部分视图是 html。因此它尝试将其解析为 json 数据并引发错误。

数据类型 - 您希望从服务器返回的数据类型。

dataType(默认值:Intelligent Guess(xml、json、script 或 html)) 类型:String 您期望从服务器返回的数据类型。如果没有指定,jQuery 将尝试根据响应的 MIME 类型推断它(XML MIME 类型将产生 XML,在 1.4 中 JSON 将产生一个 JavaScript 对象,在 1.4 中脚本将执行脚本,其他任何东西都会作为字符串返回)。可用的类型(以及作为第一个参数传递给成功回调的结果)是:

于 2013-09-18T21:33:04.853 回答
1

正如您现在所知道的,将dataType 添加到 html而不是 json。我还在 jquery 的 ajax 函数的成功/完成部分检查以下内容:

success: function (response, status, xhr) {
  var ct = xhr.getResponseHeader("content-type") || "";
  if (ct.indexOf('html') > -1) {
    // returned result is of type html, so act accordingly
    }
  else if (ct.indexOf('json') > -1) {
    // returned result is of type json, so act accordingly
  }
}

此外,有时您可能需要将从服务器收到的数据解析为 html,如下所示:

var htmldata = $.parseHTML(data); //where data is the stuff you got from server. and now use this htmldata for your processing.

parseHTML() 的参考

于 2013-09-18T21:51:00.820 回答