parserrror语法错误:意外标记< - 使用jQuery的Ajax在ASP.NET MVC 4负载管窥负载、标记、意外、语法错误

2023-09-10 16:12:25 作者:影伴人久

我用下面的Ajax调用加载的局部视图到一个div:

I'm using the following Ajax call to load a partial view into a 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语法错误:意外标记<

看来,阿贾克斯呼叫期待回JSON而不是HTML。什么我需要做的,解决这个问题?

It seems that the .ajax call is expecting json back instead of html. What do I need to do to fix this?

感谢。

推荐答案

您需要改变你的数据类型,在Ajax调用。

You need to change your datatype in the ajax call.

 dataType: "json",

 dataType: "html", 

数据类型告诉类型是JSON,但你发回的局部视图是HTML。因此,它试图解析为JSON数据,并引发错误。

Datatype tells that type is json, but you send back the partial view which is html. So it tries to parse it as json data and throws the error.

数据类型 - 你期望从服务器返回的数据类型

datatype - type of data you expect back from the server.

的数据类型(默认:智能猜测(XML,JSON,脚本或HTML))   类型:String   那你期望从服务器返回的数据的类型。如果没有指定,jQuery将尝试基于MIME类型的反应来推断它(一个XML的MIME类型会产生XML,在1.4 JSON将产生一个JavaScript对象,在1.4脚本将执行该脚本,和其他任何会返回一个字符串)。可用的类型(和传递的第一个参数你的成功回调的结果):

dataType (default: Intelligent Guess (xml, json, script, or html)) Type: String The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:

 
精彩推荐
图片推荐