一直从jquery获得一个Ajax请求的“parsererror”,我已经尝试将POST更改为GET,以几种不同的方式返回数据(创建类等),但我似乎无法找出问题是什么。

我的项目是在MVC3和我使用jQuery 1.5 我有一个下拉菜单,在onchange事件上,我触发了一个调用,以获得基于所选内容的一些数据。

下拉菜单:(这将从Viewbag中的列表中加载“Views”,并触发事件工作正常)

@{
    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:

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方法并返回:

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

但是jquery会触发$.ajax()方法的错误事件,表示“parsererror”。


请参阅@david-east的回答,了解正确的处理方法

这个答案只与jQuery 1.5中使用file:协议时的错误有关。

我最近在升级到jQuery 1.5时遇到了类似的问题。尽管得到了正确的响应,错误处理程序还是被触发。我通过使用完整事件,然后检查状态值来解决这个问题。例句:

complete: function (xhr, status) {
    if (status === 'error' || !xhr.responseText) {
        handleError();
    }
    else {
        var data = xhr.responseText;
        //...
    }
}

问题是你的控制器返回的字符串或其他对象不能被解析。 ajax调用期望得到Json作为返回。尝试像这样在控制器中返回JsonResult:

 public JsonResult YourAction()
    {
        ...return Json(YourReturnObject);

    }

希望能有所帮助。


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

我用一种更简单的方法解决了这个问题。

方法一

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

两个方法

或者你也可以像@Sagiv所说的那样,将数据返回为Json。


发生此parsererror消息的原因是,当您只是返回一个字符串或另一个值时,它不是真正的Json,因此解析器在解析它时失败。

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

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


这个问题

window.JSON.parse在$中引发错误。parseJSON函数。

<pre>
$.parseJSON: function( data ) {
...
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
...
</pre>

我的解决方案

使用requirejs工具重载JQuery。

<pre>
define(['jquery', 'jquery.overload'], function() { 
    //Loading jquery.overload
});
</pre>

js文件内容

<pre>
define(['jquery'],function ($) { 

    $.parseJSON: function( data ) {
        // Attempt to parse using the native JSON parser first
        /**  THIS RAISES Parsing ERROR
        if ( window.JSON && window.JSON.parse ) {
            return window.JSON.parse( data );
        }
        **/

        if ( data === null ) {
            return data;
        }

        if ( typeof data === "string" ) {

            // Make sure leading/trailing whitespace is removed (IE can't handle it)
            data = $.trim( data );

            if ( data ) {
                // Make sure the incoming data is actual JSON
                // Logic borrowed from http://json.org/json2.js
                if ( rvalidchars.test( data.replace( rvalidescape, "@" )
                    .replace( rvalidtokens, "]" )
                    .replace( rvalidbraces, "")) ) {

                    return ( new Function( "return " + data ) )();
                }
            }
        }

        $.error( "Invalid JSON: " + data );
    }

    return $;

});
</pre>

您的JSON数据可能是错误的。http://jsonformatter.curiousconcept.com/来验证它。


确保删除了任何调试代码或其他可能输出非预期信息的内容。有些明显,但很容易忘记在当下。


我不知道这是否仍然是实际的,但问题是编码。改为ANSI为我解决了这个问题。


如果你在IE中使用HTTP get得到这个问题,我通过设置缓存:false来解决这个问题。 由于我对HTML和json请求使用了相同的url,它会命中缓存,而不是执行json调用。

$.ajax({
    url: '/Test/Something/',
    type: 'GET',
    dataType: 'json',
    cache: false,
    data: { viewID: $("#view").val() },
    success: function (data) {
        alert(data);
    },
    error: function (data) {
        debugger;
        alert("Error");
    }
});

有很多建议要删除

dataType: "json"

虽然我承认这是可行的,但它忽略了潜在的问题。如果您确信返回的字符串确实是JSON,那么请在响应的开头寻找错误的空白。考虑在《提琴手》中看看它。我的是这样的:

Connection: Keep-Alive
Content-Type: application/json; charset=utf-8

{"type":"scan","data":{"image":".\/output\/ou...

在我的情况下,这是一个问题,PHP喷涌出不需要的字符(在这种情况下UTF文件bom)。一旦我删除了这些,它修复了问题,同时也保持

dataType: json

你应该删除dataType: "json"。然后看看魔法……这样做的原因是你正在将json对象转换为简单的字符串..因此json解析器无法解析该字符串,因为它不是json对象。

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

如果从web .net mvc/api获取操作,请确保允许获取

     return Json(data,JsonRequestBehavior.AllowGet);

您已经指定ajax调用响应数据类型为:

json的

其中实际的ajax响应不是有效的JSON,因此JSON解析器抛出一个错误。

我建议的最佳方法是将dataType更改为:

“文本”

在成功回调中验证是否返回了有效的JSON,如果JSON验证失败,在屏幕上提醒它,这样ajax调用失败的原因就很明显了。来看看这个:

$.ajax({
    url: '/Admin/Ajax/GetViewContentNames',
    type: 'POST',
    dataType: 'text',
    data: {viewID: $("#view").val()},
    success: function (data) {
        try {
            var output = JSON.parse(data);
            alert(output);
        } catch (e) {
            alert("Output is not valid JSON: " + data);
        }
    }, error: function (request, error) {
        alert("AJAX Call Error: " + error);
    }
});

如果你不想删除/更改dataType: json,你可以通过定义一个自定义转换器来覆盖jQuery的严格解析:

$.ajax({
    // We're expecting a JSON response...
    dataType: 'json',

    // ...but we need to override jQuery's strict JSON parsing
    converters: {
        'text json': function(result) {
            try {
                // First try to use native browser parsing
                if (typeof JSON === 'object' && typeof JSON.parse === 'function') {
                    return JSON.parse(result);
                } else {
                    // Fallback to jQuery's parser
                    return $.parseJSON(result);
                }
            } catch (e) {
               // Whatever you want as your alternative behavior, goes here.
               // In this example, we send a warning to the console and return 
               // an empty JS object.
               console.log("Warning: Could not parse expected JSON response.");
               return {};
            }
        }
    },

    ...

使用它,您可以自定义当响应不能解析为JSON时的行为(即使您得到一个空的响应体!)

使用这个自定义转换器,只要请求成功(1xx或2xx响应代码),.done()/success就会被触发。


我还得到了“请求返回错误:parsererror.”在javascript控制台。 在我的情况下,这不是Json的问题,但我必须传递给视图文本区域一个有效的编码。

  String encodedString = getEncodedString(text, encoding);
  view.setTextAreaContent(encodedString);

我遇到过这样的错误,但在修改我的响应后,将其发送给客户端,它工作得很好。

//Server side
response = JSON.stringify('{"status": {"code": 200},"result": '+ JSON.stringify(result)+'}');
res.send(response);  // Sending to client

//Client side
success: function(res, status) {
    response = JSON.parse(res); // Getting as expected
    //Do something
}

我也有同样的问题,翻了我的网。配置和我的队友不一样。 所以请检查你的web.config。

希望这能帮助到一些人。


我也遇到了同样的问题。我发现解决我的问题的方法是确保使用双引号而不是单引号。

echo "{'error':'Sorry, your file is too large. (Keep it under 2MB)'}";
-to-
echo '{"error":"Sorry, your file is too large. (Keep it under 2MB)"}';