开发者

JSONP / YQL: Identifying data source

I'm using JSONP to get Google through YQ开发者_开发问答L (Converting from JSON to JSONP). The success handler is called but then I want to be able to use that same handler for other YQL calls and to be able to identify in the handler function itself, which script/data source was used. Is there a way to do that?

var url = "http://query.yahooapis.com/v1/public/yql?q=SELECT%20*%20FROM%20json%20WHERE%20url%3D%22http%3A%2F%2Fmaps.googleapis.com%2Fmaps%2Fapi%2Fgeocode%2Fjson%3Flatlng%3D"+ latitude.toString()+ "%2C"+ longitude.toString() + "%26sensor%3Dtrue%22&format=json&diagnostics=true&callback=handler";

var script = document.createElement("script");
script.setAttribute("src", url);
document.getElementsByTagName("head")[0].appendChild(script);


I can't think of any way to do it other than to keep some sort of unique key for each API call you make, and then keep stuff about the call there. In order to keep the global namespace clean, you could create a single top-level object, then allocate sub-objects per query as properties of that, and give each property a reference back to the function:

function yqlHandler(json) {
  // ...
}

var uid = 1;
function makeQuery(query, data) {
  var key = 'query-' + uid++;
  yqlHandler[key] = data;
  yqlHandler[key].handler = yqlHandler;
  var url = "http://query.yahooapis.com/v1/public/yql?q=" + query + "&callback=yqlHandler." + key + ".handler";
  // ... make the JSONP call
}

That way you'll get this pointing to the "data" object used when you invoked the function. There are of course other, similar ways to do it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜