jQuery 返回“解析器错误"对于ajax请求 [英] jQuery returning "parsererror" for ajax request

查看:20
本文介绍了jQuery 返回“解析器错误"对于ajax请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从 jquery 收到一个 Ajax 请求的解析器错误",我尝试将 POST 更改为 GET,以几种不同的方式(创建类等)返回数据,但我似乎无法弄清楚是什么问题是.

Been getting a "parsererror" from jquery for an Ajax request, I have tried changing the POST to a GET, returning the data in a few different ways (creating classes, etc.) but I cant seem to figure out what the problem is.

我的项目在 MVC3 中,我使用的是 jQuery 1.5我有一个下拉菜单,在 onchange 事件中,我会根据所选内容发出呼叫以获取一些数据.

My project is in MVC3 and I'm using jQuery 1.5 I have a Dropdown and on the onchange event I fire off a call to get some data based on what was selected.

下拉列表:(这从 Viewbag 的列表中加载视图"并触发事件工作正常)

Dropdown: (this loads the "Views" from the list in the Viewbag and firing the event works fine)

@{
    var viewHtmls = new Dictionary<string, object>();
    viewHtmls.Add("data-bind", "value: ViewID");
    viewHtmls.Add("onchange", "javascript:PageModel.LoadViewContentNames()");
}
@Html.DropDownList("view", (List<SelectListItem>)ViewBag.Views, viewHtmls)

Javascript:

Javascript:

this.LoadViewContentNames = function () {
    $.ajax({
        url: '/Admin/Ajax/GetViewContentNames',
        type: 'POST',
        dataType: 'json',
        data: { viewID: $("#view").val() },
        success: function (data) {
            alert(data);
        },
        error: function (data) {
            debugger;
            alert("Error");
        }
    });
};

以上代码成功调用MVC方法并返回:

The above code successfully calls the MVC method and returns:

[{"ViewContentID":1,"Name":"TopContent","Note":"Content on the top"},
 {"ViewContentID":2,"Name":"BottomContent","Note":"Content on the bottom"}]

但是 jquery 为 $.ajax() 方法触发了错误事件,说解析器错误".

But jquery fires the error event for the $.ajax() method saying "parsererror".

推荐答案

我最近遇到了这个问题,偶然发现了这个问题.

I recently encountered this problem and stumbled upon this question.

我用更简单的方法解决了这个问题.

I resolved it with a much easier way.

方法一

您可以从对象字面量中删除 dataType: 'json' 属性...

You can either remove the dataType: 'json' property from the object literal...

方法二

或者你可以按照@Sagiv 所说的做,将你的数据作为 Json 返回.

Or you can do what @Sagiv was saying by returning your data as Json.

出现这个parsererror消息的原因是当你简单地返回一个字符串或另一个值时,它并不是真正的Json,所以解析器在解析它时会失败.

The reason why this parsererror message occurs is that when you simply return a string or another value, it is not really Json, so the parser fails when parsing it.

因此,如果您删除 dataType: json 属性,它不会尝试将其解析为 Json.

So if you remove the dataType: json property, it will not try to parse it as Json.

如果您确保将数据作为 Json 返回,使用另一种方法,解析器将知道如何正确处理它.

With the other method if you make sure to return your data as Json, the parser will know how to handle it properly.

这篇关于jQuery 返回“解析器错误"对于ajax请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆