2012-07-03 99 views
2

我正在使用另一个域上的一些json文件,所以我试图使用YQL作为代理进行crooss域请求。我是一个初学JavaScript和Web技术的人,我写的每一行代码都可以更好,但是现在如果我用你的帮助编写的代码不是那么优雅的话,这不是问题。使用YQL和MooTools的Json请求

现在我的代码是:

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的请求,但它不工作。我该怎么做?

回答

2

您可以稍微扩展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); 
    } 
}); 

,你可以使自己的DSL一样实现了airpim细节:

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(); 

https://tinker.io/c9634