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


当前回答

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

//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
}

其他回答

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

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

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

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

这个问题

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>

您已经指定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);
    }
});

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

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)"}';

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

//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
}