带有 dataType 'json' 的 jQuery ajax 方法错误解析json数据

发布于 2024-10-17 20:54:40 字数 1749 浏览 3 评论 0原文

我使用 jQuery 1.4.2 时遇到了一些无法解释的行为,我开始认为这可能是 safari 问题,而不是 jQuery 问题。让我解释一下。

我开始简单地使用 .getJSON 这样的:

$.getJSON("/challenge/results", form_data, function(data){
  //I know console.log is bad news, just a simplification.
  console.log('data', data); 
}

日志给了我一些类似

>locations: Array (1)

当我期待一个大小为 2 的数组时的信息。所以我查看了响应中的 json:

{"locations":
[{"customer_id":2,"editable":true,"id":971,"latitude":43.659208,"longitude":-79.407501,"max_zoom":25,"min_zoom":9,"name":"test"},
{"customer_id":3,"editable":true,"id":974,"latitude":36.746944,"longitude":-107.970899,"max_zoom":25,"min_zoom":9,"name":"test2"}]}

我已经大大简化了这个为了清楚起见,但据我所知,收到的 json 完全有效(通过 Rails 以编程方式生成)。 [更新: JSONLint 证实了这个假设。]

我对此感到惊讶,因此我将我的请求转换为 $.ajax 请求,看看它们之间是否存在一些细微的差异(从那时起,查看jQuery 的来源我看到 $.getJSON 只是调用 $.ajax)。

    $.ajax({
        url:"/challenge/results",
        dataType: 'json',
        data: form_data,
        cache:false,
        success: function(data, textStatus){
            console.log("data!", data, textStatus);
        });

但唉!同样的回应:

位置:数组 (1) 成功

此时,我必须承认 - 我有点傻,所以我想我会尝试一些完全注定会失败的事情:

    $.ajax({
        url:"/challenge/results",
        dataType: 'text',
        data: form_data,
        cache:false,
        success: function(data, textStatus){
            console.log("Parsed:!", $.parseJSON(data), textStatus);
        });

令我惊讶的是我的控制台显示:

位置:数组 (2) 成功

我被难住了。此时我坚持不懈地仔细研究了 jQuery 源代码 (1.4.2)。我想不出所料,ajax 函数似乎无法处理 json 解析本身(尽管,我必须承认,我不能确定)。

我完全不知道为什么会发生这种情况 - 感谢任何帮助。

I'm having some inexplicable behaviour using jQuery 1.4.2, and I'm beginning to think that it might be a safari problem, not a jQuery one. Let me explain.

I began simply enough by using .getJSON like this:

$.getJSON("/challenge/results", form_data, function(data){
  //I know console.log is bad news, just a simplification.
  console.log('data', data); 
}

And the log gave me something along the lines of

>locations: Array (1)

While I was expecting an array of size 2. So I had a look at the json in the response:

{"locations":
[{"customer_id":2,"editable":true,"id":971,"latitude":43.659208,"longitude":-79.407501,"max_zoom":25,"min_zoom":9,"name":"test"},
{"customer_id":3,"editable":true,"id":974,"latitude":36.746944,"longitude":-107.970899,"max_zoom":25,"min_zoom":9,"name":"test2"}]}

I've simplified this considerably for the sake of clarity, but as far as I can tell, the json received is perfectly valid (generated programmatically through rails). [Update: JSONLint confirms this hypothesis.]

I was surprised by this, so I converted my request to a $.ajax request to see if there was some subtle difference between them (since then, looking in the source of jQuery I see that $.getJSON simply calls $.ajax).

    $.ajax({
        url:"/challenge/results",
        dataType: 'json',
        data: form_data,
        cache:false,
        success: function(data, textStatus){
            console.log("data!", data, textStatus);
        });

But alas! The same response:

locations: Array (1) success

At this point, I must admit - I was getting a bit silly, so I thought I would try something completely bound to fail:

    $.ajax({
        url:"/challenge/results",
        dataType: 'text',
        data: form_data,
        cache:false,
        success: function(data, textStatus){
            console.log("Parsed:!", $.parseJSON(data), textStatus);
        });

Much to my surprise my console read:

locations: Array (2) success

I was stumped. At this point I dug in my heels and took a long hard look at the jQuery source (1.4.2). I suppose unsurprisingly, the ajax function seems not to handle the json parsing itself (although, I must admit, I can't be sure).

I'm totally at a loss for why this could be happening - any help is appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

如梦 2024-10-24 20:54:40

也许我错过了一些东西,但我注意到您的 JSON 是一个具有单个属性(“locations”)的对象,其值是一个数组。你有没有尝试过:

$.getJSON("/challenge/results", form_data, function(data){
  //I know console.log is bad news, just a simplification.
  console.log('data', data.locations); 
}

Perhaps I missed something, but I notice that your JSON is an object that has a single property ("locations") with an array as it's value. Have you tried:

$.getJSON("/challenge/results", form_data, function(data){
  //I know console.log is bad news, just a simplification.
  console.log('data', data.locations); 
}
柠檬 2024-10-24 20:54:40

试试这个:

 // Enables for all serialization
jQuery.ajaxSettings.traditional = true;

// Enables for a single serialization
jQuery.param( stuff, true );

// Enables for a single Ajax requeset
$.ajax({ data: stuff, traditional: true });

嘿,你的问题似乎与嵌套参数序列化有关。正如 jQuery 1.4 发行说明所说:

Query 1.4 使用 PHP 流行的方法在 jQuery.param 中添加了对嵌套参数序列化的支持,并受 Ruby on Rails 支持。例如,{foo: ["bar", "baz"]} 将被序列化为“foo[]=bar&foo[]=baz”。

在 jQuery 1.3 中,{foo: ["bar", "baz"]} 被序列化为“foo=bar&foo=baz”。但是,无法使用这种方法对单元素数组进行编码。如果您需要旧的行为,您可以通过设置传统的 Ajax 设置(全局通过 jQuery.ajaxSettings.traditional 或根据具体情况通过传统标志)将其重新打开。

try this:

 // Enables for all serialization
jQuery.ajaxSettings.traditional = true;

// Enables for a single serialization
jQuery.param( stuff, true );

// Enables for a single Ajax requeset
$.ajax({ data: stuff, traditional: true });

hey,your problem seems like to be have something to do with the nested param serialization.just as what the jQuery 1.4 release note say:

Query 1.4 adds support for nested param serialization in jQuery.param, using the approach popularized by PHP, and supported by Ruby on Rails. For instance, {foo: ["bar", "baz"]} will be serialized as “foo[]=bar&foo[]=baz”.

In jQuery 1.3, {foo: ["bar", "baz"]} was serialized as “foo=bar&foo=baz”. However, there was no way to encode a single-element Array using this approach. If you need the old behavior, you can turn it back on by setting the traditional Ajax setting (globally via jQuery.ajaxSettings.traditional or on a case-by-case basis via the traditional flag).

守护在此方 2024-10-24 20:54:40

应使用 Webkit 检查器的调试器而不是控制台日志记录,后者可以显示对象的未来状态。这是导致此问题的原因,因为列表在 console.log 行之后的代码中被修剪,从而导致了意外的行为。

The Webkit inspector's debugger should be used instead of console logging, which can show the object in a future state. This was the cause of this problem as the list was being trimmed in code after the console.log line, which resulted in the unexpected behaviour.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文