使用原型解析JSON结果的问题

问题描述 投票:1回答:2

我的服务返回以下JSON对象,其Content-Type标头设置为“ application / javascript”。按照json.org] 2上的说明将其包装在parens中,但是我尝试了有无parens。没有parens,它将通过jsonlint的验证。

({
  "products": {
    "itemId": "0",
    "productId": "1234",
    "quantity": "4",
    "rank": "12",
    "subProductId": ""
  },
  "txnId": "1"
})

如果我明确评估响应,如下所示,则没有问题:

var form = $('productListRequestForm');
form.request({
  onSuccess: function(response) {
    var json = eval(response.responseText);
    rebuildWishlistTable(json);
  },
  onFailure: function(response) {
    alert("AJAX request failed: " + response.responseText);
  }
});

但是,如果我依靠原型解析响应并将解析结果作为第二个参数传递给函数,如下所示,则该值始终为null。根据Prototype docs,这应该起作用。是否有我所缺少的东西,或者他们所缺少的东西?

var form = $('productListRequestForm');
form.request({
  onSuccess: function(response, json) {
    rebuildWishlistTable(json);
  },
  onFailure: function(response) {
    alert("AJAX request failed: " + response.responseText);
  }
});
javascript json prototype
2个回答
1
投票

它看起来像是原型中的错误。

在修订版1.6.1的第1497行,有以下代码:

  var contentType = response.getHeader('Content-type');
  if (this.options.evalJS == 'force'
      || (this.options.evalJS && this.isSameOrigin() && contentType
      && contentType.match(/^\s*(text|application)\/(x-)?(java|ecma)script(;.*)?\s*$/i)))
    this.evalResponse();

注意,evalResponse()的返回值不会做任何事情。如果然后转到该函数的定义:

  evalResponse: function() {
    try {
      return eval((this.transport.responseText || '').unfilterJSON());
    } catch (e) {
      this.dispatchException(e);
    }
  },

[在Prototype网站上发布了一个错误,并关闭了关于我对JSON有“若干误解”的评论,并且不应该使用错误报告系统来获取帮助。有趣的是,我以为我指出了他们扔掉返回值的地方。

如果其他人可能也有类似的情况,我正在编辑我的问题以显示有效和无效的代码,并将接受此答案。


0
投票

用括号括起来

eval("({\"products\"": {\"itemId\": \"0\", \"productId\": \"1234\", \"quantity\": \"4\", \"rank\": \"12\", \"subProductId\": \"\"}, \"txnId\": \"1\"})")

将为您工作

© www.soinside.com 2019 - 2024. All rights reserved.