jQuery为ajax请求返回“parsererror”

时间:2011-02-21 00:54:28

标签: javascript c# jquery asp.net json

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

我的项目是MVC3,我正在使用jQuery 1.5 我有一个Dropdown,在onchange事件中,我根据所选内容发出一个调用来获取一些数据。

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

@{
    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”。

17 个答案:

答案 0 :(得分:266)

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

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

方法一

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

方法二

或者您可以将数据作为Json返回,以表达@Sagiv所说的内容。


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

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

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

答案 1 :(得分:27)

请参阅@ david-east的answer以了解处理问题的正确方法

此答案仅与使用file:protocol时的bug with jQuery 1.5相关。

最近升级到jQuery 1.5时遇到了类似的问题。尽管获得了正确的响应,但错误处理程我通过使用complete事件然后检查状态值来解决它。 e.g:

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

答案 2 :(得分:15)

您已将ajax呼叫响应 dataType 指定为:

  

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

答案 3 :(得分:10)

问题是你的控制器返回了无法解析的字符串或其他对象。 ajax调用有望让Json得到回报。尝试在控制器中返回JsonResult:

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

    }

希望它有所帮助:)

答案 4 :(得分:5)

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

答案 5 :(得分:4)

有很多建议需要删除

dataType: "json"

虽然我承认这是有效的,但忽略了潜在的问题。如果您确信返回字符串确实是JSON,那么在响应开始时查找错误的空格。考虑在小提琴手中看一下。我看起来像这样:

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

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

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

dataType: json

答案 6 :(得分:1)

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

答案 7 :(得分:0)

我不知道这是否仍然存在,但问题在于编码。更改为ANSI解决了我的问题。

答案 8 :(得分:0)

如果在IE中使用HTTP GET遇到此问题,我通过设置cache: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");
    }
});

答案 9 :(得分:0)

你应该删除dataType:&#34; json&#34;。然后看看魔术...这样做的原因是你将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");
    }
 });
};

答案 10 :(得分:0)

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

     return Json(data,JsonRequestBehavior.AllowGet);

答案 11 :(得分:0)

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

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

答案 12 :(得分:0)

我遇到了这样的错误,但是在修改了响应并将其发送给客户端之前,它工作正常。

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

答案 13 :(得分:0)

我遇到了同样的问题,原来我的web.config与队友不一样。 因此,请检查您的web.config

希望这对某人有帮助。

答案 14 :(得分:0)

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

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

答案 15 :(得分:-1)

问题

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 tool重载JQuery。

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

jquery.overload.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>

答案 16 :(得分:-1)

如果您不想删除/更改dataType: json ,则可以通过定义自定义converter来覆盖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