繁体   English   中英

jQuery 为 ajax 请求返回“解析器错误”

[英]jQuery returning “parsererror” for ajax request

对于 Ajax 请求,从 jquery 收到“解析器错误”,我尝试将 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() 方法触发错误事件,说“解析器错误”。

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

我用更简单的方法解决了它。

方法一

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

方法二

或者,您可以通过将数据返回为Json来执行@Sagiv 所说的操作。


出现此parsererror错误消息的原因是,当您简单地返回字符串或其他值时,它并不是真正的Json ,因此解析器在解析它时会失败。

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

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

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

此答案仅使用 file: 协议时jQuery 1.5错误有关。

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

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

您已将 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);
    }
});

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

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

    }

希望能帮助到你 :)

有很多建议可以删除

dataType: "json"

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

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

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

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

dataType: json

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

您应该删除数据类型:“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);

我还收到“请求返回错误:解析器错误”。 在 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与我的队友不一样。 所以请检查您的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)"}';

问题

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>

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>

如果您不想删除/更改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

我面临着同样的问题,但实际问题出在JSON格式设置而不是JSON,我的答复是HTML形式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM