2

我想将 YQL 查询的结果保存在 javascript 对象中

我的查询:

SELECT * FROM html WHERE url="http://myurl.com" 和 xpath="/html/body/center/table[1]/tr"

我要怎么继续?我阅读了 YQL 的文档,但我认为它真的很复杂。我也在stackoverflow上搜索过,但它并没有真正帮助我。

该对象应该就像 JS 中的普通 JSON 对象一样。

问候

4

2 回答 2

1

您可能无法一次性保存整个内容,但您可以通过获取您需要的信息来保存数据,将其组织成一个数组,然后保存该数组:

function getXML(Your_XML_URL) {
// Build the YQL query
var qryRSS = 'select * from rss where url=' + '"' + feed + '"';

// Initiate the YQL query
$.getJSON("http://query.yahooapis.com/v1/public/yql",
    {
        // These are the settings for your API call
        q: qryRSS,
        format: "json"
    },
    // Take the data you got from the YQL server and output it to the screen. The variable "data" holds the JSON you got back from the YQL server.
    function (data) {
        var myArrayName = [];
        // Create an object for each entry. If you don't want every entry in the XML files you can change data.query.results.item.length to whatever number you want.
        for (var i = 0; i < data.query.results.item.length; i += 1) {
            var singleEntry = {};
            dataLoc = data.query.results.item[i];

            var singleEntry.title = dataLoc.title;           //You would replace these
            var singleEntry.pub = dataLoc.pubDate;           //with the names of the tags
            var singleEntry.image = dataLoc.thumbnail.url;   //in your XML file.
            var singleEntry.url = dataLoc.link;
            var singleEntry.desc = dataLoc.description;

            //Add your object to the array.
            myArrayName.push(singleEntry);

        }
        localStorage.setItem("mySavedItem", JSON.stringify(myArrayName));
    });
}

然后您可以稍后通过以下方式检索该信息:

var myXMLArray = JSON.parse(localStorage.getItem("mySavedItem"));
console.log(myXMLArray[0].title);
console.log(myXMLArray[2].pub);
于 2014-08-21T16:58:51.043 回答
1

您可以使用 JSONP 方法获取此数据。脚本:

<script src="http://query.yahooapis.com/v1/public/yql?q=SELECT%20*%20FROM%20html%20WHERE%20url%3D%22http%3A%2F%2Fghse%3A12-13%40www.ghse.de%2Fvplan%2F12%2Fc%2Fc00082.htm%22%20and%20xpath%3D%22%2Fhtml%2Fbody%2Fcenter%2Ftable%5B1%5D%2Ftr%22&format=json&callback=callback"></script>

用于处理响应的回调:

function callback(data) {
    console.log(data);
}

http://jsfiddle.net/bdCHZ/

另请查看 YQL 控制台测试器以获取详细信息。

这只是一个如何手动检索此 JSON 的示例。您可以使用 jQuery 等来发出 JSONP 请求。

于 2013-03-17T20:39:07.023 回答