javascript - 语法 :Error JSON. 解析,尝试为 protovis 加载数据时

标签 javascript ajax json protovis

您好,我正在学习如何使用 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/它有效。所以一定是代码。

最佳答案

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

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()。

关于javascript - 语法 :Error JSON. 解析,尝试为 protovis 加载数据时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4696081/

相关文章:

javascript - 选择数组javascript的一部分

java - 从 javascript 调用 java web 服务

javascript - XMLHttpRequestObject.onreadystatechange...有必要吗?

javascript - Webpack 中的热模块替换到底是什么?

javascript - Gulp - 使用自定义文件夹构建文件

javascript - 在 Canvas 上操纵面部细节

javascript - 将 jquery 升级到 1.9.1 后,Ajax.Actionlink onsuccess 脚本停止工作

java - 适用于所有格式的通用阅读器?

javascript - 在 JavaScript 中解析 OData 元数据

mysql - 如何使用 MySQL 查询 JSON 对象内未修改的时间戳?