【问题标题】:How to read data from in Javascript如何从 Javascript 中读取数据
【发布时间】:2015-04-29 06:30:49
【问题描述】:

我正在尝试使用 Javascript 从 "http://table.finance.yahoo.com/table.csv?s=000001.sz" 的 yahoo Finance 读取股票数据,它返回一个 csv 文件并将数据转换为 http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-ohlcv.json&callback= 中的 json 格式?用于highcharts。

我尝试使用 $.ajax get 和 jquery.get 但都不起作用。有人可以告诉我如何从 url 读取数据并将其转换为 json 吗?非常感谢。

【问题讨论】:

  • 你需要javascript吗?你不能用别人。就像 python 有一个内置的 CSV 解析器一样。否则,您需要自己获取数据,解析并将其转换为 json。不过,我可以为您提供帮助
  • 我认为您应该使用 jQuery.ajax 和 jQuery.get 或 $.ajax 和 $.get。保持统一。 $ 和 jQuery 是一回事。 $===jQuery 返回 true 但 jquery 和 jQuery 不一样。如果您不确定是否在哪里使用了 jquery 而不是 jQuery,请在任何 IDE 中进行区分大小写的搜索并替换为 jQuery 或在开头,请执行 var jquery= jQuery 以便您的代码正常工作,但我不建议这样做
  • @Ronnie 非常感谢。我使用了 jQuery,但我认为这不是问题所在。我只是想知道js中是否有与requests.get()或urllib2.urlopen()具有相同功能的东西
  • 如果可能的话,这对 JavaScript 来说应该是相当麻烦的。我希望你正在使用 PHP。
  • @Ashesh 非常感谢。

标签: javascript json highcharts


【解决方案1】:

这可以通过 PHP 轻松完成。

<?php
file_put_contents("data.csv", fopen("http://table.finance.yahoo.com/table.csv?s=000001.sz", 'r'));

//reads the CSV file and save value into an associative array
function csv_to_array($filename = '', $delimiter = ',')
{
    if (!file_exists($filename) || !is_readable($filename))
        return FALSE;

    $header = NULL;
    $data   = array();
    if (($handle = fopen($filename, 'r')) !== FALSE) {
        while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
            if (!$header)
                $header = $row;
            else
                $data[] = array_combine($header, $row);
        }
        fclose($handle);
    }
    return $data;
}

$arr = csv_to_array('data.csv');

//<pre></pre> tags appear only to prevent white-space collapsing

//prints the associative array
echo "<pre>";
print_r($arr);
echo "</pre>";

//displays the the JSON
echo "<pre>";
echo json_encode($arr, JSON_PRETTY_PRINT);
echo "</pre>";
?>

现在,根据 Highcharts API 可接受的 JSON 格式,您需要调整如何将数组编码为 JSON。 如果传入数据的大小很大,也要避免使用JSON_PRETTY_PRINT

【讨论】:

    【解决方案2】:

    我猜您正面临跨域问题。对跨域请求使用 jsonp 调用。使用类似的东西

     $.ajax({
        url : "http://xx.xx.xx.xx/xxx/xxx",
        type: "GET",
        dataType: "jsonp",
        jsonp : "callback",
        success: function(data) {alert("Success");},
        error: function(data) { alert("Error"); }
    
        });        
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-29
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      • 2011-05-22
      • 1970-01-01
      • 2010-10-23
      • 1970-01-01
      相关资源
      最近更新 更多