首页 文章

jQuery为ajax请求返回“parsererror”

提问于
浏览
155

从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” .

14 回答

  • 12

    如果你在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");
        }
    });
    
  • 27

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

    我用一种更容易的方式解决了这个问题 .

    Method One

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

    Method Two

    或者你可以通过将数据作为 Json 来执行@Sagiv所说的 .


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

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

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

  • 4

    See the answer by @david-east for the correct way to handle the issue

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

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

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

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

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

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

    希望能帮助到你 :)

  • 0

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

  • 0

    有很多建议要删除

    dataType: "json"
    

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

    Connection: Keep-Alive
    Content-Type: application/json; charset=utf-8
    
    {"type":"scan","data":{"image":".\/output\/ou...
    

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

    dataType: json
    
  • -1

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

  • -1

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

  • 246

    你应该删除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");
        }
     });
    };
    
  • 0

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

    return Json(data,JsonRequestBehavior.AllowGet);
    
  • 9

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

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

    The problem

    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>
    

    My solution

    使用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>
    
  • 0

    If you don't want to remove/change 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 .

相关问题