2

嗨,我正在学习如何使用 protovis,到目前为止一切都很好,但现在我偶然发现了一个我似乎无法解决的问题。

以下是代码。(我的标题中加载了最新的 jquery

<script type="text/javascript+protovis"> 
var dataURL = "http://eagereyes.org/media/2010/protovis-primer/earthquakes.json";

var JSONdata = $.ajax({ type: "GET", url: dataURL, async: false }).responseText;
var earthquakes = JSON.parse(JSONdata);

var width = 560;
var height = 245;

var barWidth = width/earthquakes.length;
var gap = 2;

new pv.Panel().width(width).height(height+5)
    .add(pv.Bar)
        .data(earthquakes)
        .bottom(0)
        .width(barWidth-gap)
        .height(function(d) d.Magnitude * (height/9))
        .left(function() this.index * barWidth)
    .root.render();

当我在 Firefox 中尝试此操作时,我收到此警报:

Syntax:Error JSON.parse

我已经在http://www.jsonlint.com/上验证了 JSON 。所以问题一定出在其他地方。

有谁知道这里发生了什么?

编辑

我尝试在 protoviewer 应用程序中加载相同的数据:http ://www.rioleo.org/protoviewer/ 它可以工作。所以它必须是代码。

4

4 回答 4

2

您是否尝试过常规的异步回调而不是同步方法?喜欢:

var dataURL = "http://eagereyes.org/media/2010/protovis-primer/earthquakes.json";

$.ajax({
  type: "GET",
  url: dataURL,
  success: function(response) {
    var earthquakes = JSON.parse(JSONdata);

    var width = 560;
    var height = 245;

    var barWidth = width/earthquakes.length;
    var gap = 2;

    new pv.Panel().width(width).height(height+5)
        .add(pv.Bar)
            .data(earthquakes)
            .bottom(0)
            .width(barWidth-gap)
            .height(function(d) d.Magnitude * (height/9))
            .left(function() this.index * barWidth)
        .root.render();     
  }
});

此外,该 JSON 文件是否位于发出请求的页面在地址栏中显示的同一服务器上(确切地说http://eagereyes.org)?

最后,不需要手动 JSON.parse() 步骤。如果添加dataType: 'json'参数,$.ajax() 将自动反序列化为 JSON,并在可用的情况下使用 JSON.parse()。

于 2011-01-14T21:45:03.887 回答
0

您使用的是哪个浏览器?一些浏览器没有定义JSON对象。JSON您可以从下面的 URL 下载脚本,如果该对象不存在,该脚本将定义该对象。

https://github.com/douglascrockford/JSON-js

可以检查是否JSON定义如下:

alert(JSON);

更新

好的,接下来我要做的是检查 ajax 调用是否实际上返回了正确的数据。更改您的代码以打印从 ajax 调用返回的 JSON。

var JSONdata = $.ajax({ type: "GET", url: dataURL, async: false }).responseText;
alert(JSONdata);
var earthquakes = JSON.parse(JSONdata);
于 2011-01-14T21:26:46.040 回答
0

Add a semi-colon ; to the end of your response

于 2011-01-14T21:29:30.063 回答
0
$.ajax({
            type: "POST",
            url: "saveChangesInEditing.php",
            data: idObject,
            success: function(data){
                         dataObject = JSON.parse(data);
                         $("input[name = 'id']").val(dataObject.id);
                         $("input[name='full_name']").val(dataObject.full_name);
                         $("input[name='sport']").val(dataObject.sport);
                         $("input[name='idol']").val(dataObject.idol);
                    },
            error: function(data){
                     alert("error!" + data);
                   }
        });
于 2012-10-15T01:44:07.640 回答