一直从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”。


当前回答

这个问题

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>

其他回答

如果你不想删除/更改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就会被触发。

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

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

方法一

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

两个方法

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


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

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

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

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

有很多建议要删除

dataType: "json"

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

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

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

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

dataType: json

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

希望这能帮助到一些人。