我正在另一个域上处理一些 json 文件,因此我尝试使用 YQL 作为代理发出跨域请求。我是 javascript 和网络技术的初学者,我写的每一行代码都可以更好,但现在如果我在你的帮助下编写的代码不是那么优雅,那也不是问题。
现在我的代码是:
function GetUrl() {
var link = "http://m.airpim.com/json/public/search?q=variabile&k=&e=1",
name = document.id('s').get('value') || '*';
return link.replace("variabile", name);
}
function Ricerca() {
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from json where url="' + GetUrl() + '"') + '&format=json&diagnostics=false&callback=';
return yql;
}
function LavoroJson() {
var ciao = new Request.JSONP({
url: Ricerca(),
onComplete: function(data) {
// Log the result to console for inspection
alert(ciao.toSource());
}
}).send();
}
在我的想法中,我应该使用 YQL 来执行 json 的请求,但它不起作用。我该怎么做?
最佳答案
您可以稍微扩展 Request.JSONP 类。
Request.YQLJSON = new Class({
// gets basic info such as country and latitude data
Extends: Request.JSONP,
options: {
log: !true,
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22{location}%22&format=json"
},
initialize: function(location, options) {
this.parent(options);
if (!location)
return;
this.options.url = this.options.url.substitute({location: encodeURIComponent(location)});
},
success: function(data, script) {
this.parent(data, script);
}
});
并且您可以为airpim 细节制作自己的类似 DSL 的实现:
Request.airpim = new Class({
Extends: Request.YQLJSON,
options: {
suburl: "http://m.airpim.com/json/public/search?q={search}&k=&e=1"
},
initialize: function(query, options) {
this.parent(this.options.suburl.substitute({
search: encodeURIComponent(query)
}), options);
}
});
像这样使用:
new Request.airpim("*", {
onSuccess: function(data) {
console.log(data.query.results.json);
}
}).send();
关于javascript - 使用 YQL 和 MooTools 进行 Json 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11308663/