问题
I was just playing with Google Fusion Tables and I was wondering how I could load a csv from the client side. So far I've tried several options:
From actionscript 3.0:
var r:URLRequest = new URLRequest("https://www.google.com/fusiontables/exporttable?query=select%20*%20from%203685185%20");
r.method = URLRequestMethod.GET;
var l:URLLoader = new URLLoader(r);
l.addEventListener(Event.COMPLETE,loaded);
l.addEventListener(HTTPStatusEvent.HTTP_STATUS,onHTTPStatus);
function onHTTPStatus(event:HTTPStatusEvent):void{
trace(event.status);
}
function loaded(event:Event):void{
trace(this.loaderInfo.url,event.target.data);
}
From actionscript 2.0:
var vars:LoadVars = new LoadVars();
vars.onLoad = function(loaded):Void{
if(loaded) trace(unescape(this));
else trace("error loading data");
}
vars.onHTTPStatus = function(status:Number):Void{
trace(status);
}
vars.load("http://www.google.com/fusiontables/exporttable?query=select%20*%20from%203685185%20&r="+new Date().getMilliseconds());
From javascript:
$.get('https://www.google.com/fusiontables/exporttable?query=select%20*%20from%203685185%20',
function(data) { alert(data); });
In actionscript everything works in the standalone player, but not online which smells like some sort of security sandbox issue. In JS I get this:
XMLHttpRequest cannot load https://www.google.com/fusiontables/exporttable?query=select%20*%20from%203685185%20. Origin http://lifesine.eu is not allowed by Access-Control-Allow-Origin.
The table I'm querying is public and exportable. I've also tried the call using Simple REST Client on Chrome and got the right response. Any hints on how what I might be missing ?
回答1:
I can only speak to the javascript approach. You need to use JSONP to retrieve the results due to browser cross domain access restrictions. Luckily Fusion Tables supports JSONP. I posted some example code in this answer. Another approach would be to use the google.visualization library and there's some sample code in this answer.
UPDATE @george-profenza
2 points. The URL for the FT JSONP api is different. And for jsonp you must add a callback parameter. Try this:
var queryurl = 'https://fusiontables.googleusercontent.com/fusiontables/api/query?sql=select%20*%20from%203685185%20&jsonCallback=?';
Also here's an example success function:
function dataHandler(data, textStatus, jqXHR) {
alert(textStatus);
var cols = data.table.cols;
var rows = data.table.rows;
for (var i = 0; i < cols.length; i++) {
alert(cols[i]);
}
for (var i = 0; i < rows.length; i++) {
for(j=0; j < rows[i].length; j++) {
alert(rows[i][j]);
}
}
}
来源:https://stackoverflow.com/questions/10341740/how-can-i-load-a-fusion-tables-csv-from-a-client-application