gpt4 book ai didi

javascript - 尝试读取 csv 数据时未捕获的语法错误

转载 作者:行者123 更新时间:2023-11-29 19:10:30 25 4
gpt4 key购买 nike

我正在使用 Mootools JSONP 从返回 CSV 文件的 url 中读取。现在,CSV (Adj Close) 中的一列有一个空格,它会中止文件读取并将错误抛出到控制台。我有哪些选项(如果有)来读取 csv 数据?

我收到错误:

table.csv:1 Uncaught SyntaxError: Unexpected identifier

还有一个附加信息:我可以看到 csv 文件正在下载到浏览器中。我不能从浏览器读取它吗?

var url = 'http://ichart.yahoo.com/table.csv?s=GOOG&a=0&b=1&c=2000&d=0&e=31&f=2010&g=w&ignore=.csv';

loaderJSONP(url);

loaderJSONP = function(URL) {
//Get Data
new Request.JSONP({
url: URL,
onSuccess: function(response) {
show_response(response, $('post'));
}
}).send();

show_response = function(obj, result) {
console.log(obj);
};
}

最佳答案

添加 answer I gave on GitHub在这里,以供将来引用:

The idea of JSONP is that the resource returns "JSON with Padding", where the JSON is a value in JavaScript Object Notation, and the Padding is a function call, with as aim to get around same-origin policies.

  • JSON: {"a":"b"}
  • JSONP: myCallbackFunction({"a":"b"})

So basically, the JSONP resource is expected to return valid, executable JavaScript code, and you (or in this case MooTools More) provide(s) the definition of "myCallbackFunction". The resource location is then appended with &callback=myCallbackFunction and injected as src of an HTML <script> tag. The tag is injected into the document, and the function is called with the data supplied, so you can go about your things. (The function itself won't be called "myCallbackFunction" by MooTools, in case you're wondering.)

The resource you request from ichart.yahoo.com returns a CSV format and I doubt that it supports any callback function padding, meaning it probably can't work this way.

I can see two options:

  1. Look at Yahoo's developer console, see if the yahoo.finance.historicaldata table suits your needs, or if there is another way to fetch your data through YQL.
  2. Fetch the CSV through other means (some server), and supply it back to your application (with optional pre parsing, so you don't have to parse the CSV in JavaScript).

关于选项 2 的后续问题的答案,关于为什么没有结果:

You'll have to use the callback value passed as query parameter.

Try something like this (untested):

function print_json($data) {
$json = json_encode($data);

if (array_key_exists('callback', $_GET) && !preg_match('/[^\w.]/', $_GET['callback'])) {
header('Content-type: application/javascript; charset=utf-8');
echo $_GET['callback'], '(', $json, ')';
} else {
header('Content-type: application/json; charset=utf-8');
echo $json;
}
}

关于javascript - 尝试读取 csv 数据时未捕获的语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39241740/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com