简体   繁体   English

jQuery.ajax()+空JSON对象=解析错误

[英]jQuery.ajax() + empty JSON object = parse error

I get a parse error when using jQuery to load some JSON data. 使用jQuery加载一些JSON数据时,我得到一个解析错误。 Here's a snippet of my code: 这是我的代码片段:

jQuery.ajax({
    dataType: "json",

    success: function (json)
    {
        jQuery.each(json, function ()
        {
            alert(this["columnName"]);
        });
    }
});

I get no errors when parsing a non-empty JSON object. 解析非空JSON对象时没有错误。 So my guess is that the problem is with my serializer. 所以我的猜测是问题出在我的序列化器上。


Question is: how do I format an empty JSON object which jQuery won't consider malformed? 问题是:如何格式化jQuery不会考虑格式错误的空JSON对象?

This is what I've tried so far, with no success: 这是我到目前为止所尝试的,没有成功:

{[]}

{[null]}

{}

{null}


{"rows": []}

{"rows": null}

{"rows": {}}



UPDATE: 更新:

I can understand that I've been somewhat vague--let me try and clarify: 我能理解我有点模糊 - 让我试着澄清一下:

Parsing of the JSON object is not the issue here--JQuery is - I think. 解析JSON对象不是问题 - JQuery是 - 我想。

jQuery throws a parse-error (invokes the error function). jQuery抛出一个解析错误(调用错误函数)。 It seems like jQuery's internal JSON validation is not accepting any of the before mentioned objects. 似乎jQuery的内部JSON验证不接受任何前面提到的对象。 Not even the valid ones. 甚至不是有效的。

Output of the error function is: 错误函数的输出是:

XMLHttpRequest: XMLHttpRequest readyState=4 status=200 XMLHttpRequest: XMLHttpRequest readyState = 4 status = 200
textStatus: parsererror textStatus: parsererror
errorThrown: undefined errorThrown:未定义

This goes for all of the before mentioned objects. 这适用于前面提到的所有对象。

解决方案是从服务器返回204而不是200的状态代码,204是“无内容”并且它将在不尝试调用解析器时返回成功

Firstly {[]} , {[null]} , and {null} won't work because they are all invalid JSON objects (as verified by the JSON validator ). 首先{[]}{[null]}{null}将不起作用,因为它们都是无效的JSON对象(由JSON验证器验证 )。

The remaining objects are all valid JSON objects, so your success function should be getting invoked. 其余对象都是有效的JSON对象,因此应该调用您的success函数。

If you pass a non-array or array-like object object then the each function will enumerate your json object by its named properties. 如果传递非数组或类数组的对象对象,则each函数将通过其命名属性枚举您的json对象。 In the case of your three objects that each have a rows property this will be set to [] , null , and {} respectively, none of which have a columnName attribute so an undefined error will be thrown. 如果您的三个对象都有一个rows属性, this将分别设置为[]null{} ,其中没有一个具有columnName属性,因此将抛出未定义的错误。

Your {} object on the other hand has no properties, so shouldn't be causing an error because the each call will loop 0 times. 另一方面,您的{}对象没有属性,因此不应该导致错误,因为each调用将循环0次。 What does the following line display if you add it as the first line in your success function? 如果将其添加为success函数的第一行,则显示以下行?

alert(typeof json + ' ' + (json == null));

Your web service may be returning null. 您的Web服务可能返回null。 I've found that returning null from a web service call returns a response with status code 200, "Ok", but jQuery throws a parseerror afterwards. 我发现从Web服务调用返回null会返回状态代码为200的响应,“Ok”,但jQuery之后会抛出一个parseerror。

If this is the case, it has nothing to do with what you're sending up to the server, and everything with what the server is sending back. 如果是这种情况,它与您发送到服务器的内容以及服务器发回的内容无关。

If you're able to change the web service, you might want to try returning an empty JSON object, or a default value instead of Null. 如果您能够更改Web服务,则可能需要尝试返回空JSON对象或默认值而不是Null。 Alternatively, you could check for this error scenario in your error handler, knowing that this means your call returned null. 或者,您可以在错误处理程序中检查此错误情况,因为这意味着这意味着您的调用返回null。

you are looking for this: 你在找这个:

[]

an empty array. 一个空数组。 That is, if you plan to iterate over it right away, then what you need is an array. 也就是说,如果你打算立即迭代它,那么你需要的是一个数组。

Instead of: 代替:

$(json).each(function () { ... });

I think you want to be using: 我想你想要使用:

$.each(json, function () { ... });

From the jQuery.each documentation : jQuery.each文档

This function is not the same as $().each() - which is used to iterate, exclusively, over a jQuery object. 这个函数与$()。each()不同 - 它用于独占于jQuery对象进行迭代。 This function can be used to iterate over anything. 此函数可用于迭代任何内容。

Did you verify if the JSON is returned correctly in the first place before the each? 您是否确认JSON是否在每个之前首先正确返回? Set the empty value as {}, and verify if it is like that before .each 将空值设置为{},并验证它是否与之前相同.each

Also it would help to know how your JSON looks like when there is data. 另外,当有数据时,了解JSON的外观也会有所帮助。

Had this problem as well, and solved it by using the jsonserializer in my web service to format an empty string. 也有这个问题,并通过在我的Web服务中使用jsonserializer来格式化空字符串来解决它。 result is was "\\"\\"" essentially "" ; 结果是“\\”\\“”基本上“” ;

I was experiencing similar problems when requesting valid JSON from the server. 从服务器请求有效的JSON时,我遇到了类似的问题。

My server was serving the content-type of text/javascript 我的服务器正在提供text / javascript的内容类型

I was not using the optional jQuery.ajax setting of 'dataType' so jQuery was interpretting the output a javascript (eg padded JSON), not neat JSON. 我没有使用'dataType'的可选jQuery.ajax设置,所以jQuery正在解释输出javascript(例如填充的JSON),而不是整齐的JSON。

Adding a dataType:'JSON' to the settings object passed to jQuery's ajax method solved the problem. 向传递给jQuery的ajax方法的设置对象添加dataType:'JSON'解决了这个问题。

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

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