有什么不同?为什么 JavaScript 不能处理这两个响应?

What's the difference? Why can't JavaScript work with both responses?

我正在使用尽可能多的 Javascript 编写 RSS-reader。由于同源策略,我必须使用另一个解决方案请求提要的 XML 文件。首先我使用了雅虎!查询语言 (YQL) 但为了独立,我尝试编写一些 PHP 代码。尽管两种解决方案的响应几乎相同(使用 YQL 时有一些 Yahoo 数据),但我使用 PHP 的解决方案不起作用。

YQL解决方案

function yahoo() {
// request the xml
$.get("https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%3D'http%3A%2F%2Fnews.yahoo.com%2Frss%2Ftopstories'&diagnostics=false", function (data) {
// save the data (title, content, link, date) to the localStorage
    $(data).find("item").each(function () {
        el = $(this);
        if (!el.find("title").text() || !el.find("description").text() || !el.find("link").text() || !el.find("pubDate").text()) {
            console.log("errorEntry");
        } else {
            localStorage.setItem('titleEntry' , el.find("title").text());
            localStorage.setItem('contentEntry' , el.find("description").text());
            localStorage.setItem('linkEntry' , el.find("link").text());
            localStorage.setItem('dateEntry' , el.find("pubDate").text());
    }
    });
});
}

我的解决方案 JavaScript:

function php() {
// request the xml
$.get("rss_request.php?feedUrl=http://news.yahoo.com/rss/topstories", function (data) {
// save the data (title, content, link, date) to the localStorage
    $(data).find("item").each(function () {
        el = $(this);
        if (!el.find("title").text() || !el.find("description").text() || !el.find("link").text() || !el.find("pubDate").text()) {
            console.log("errorEntry");
        } else {
            localStorage.setItem('titleEntry' , el.find("title").text());
            localStorage.setItem('contentEntry' , el.find("description").text());
            localStorage.setItem('linkEntry' , el.find("link").text());
            localStorage.setItem('dateEntry' , el.find("pubDate").text());
            localStorage.setItem('typeEntry' , "rss");
    }
    });
});
}

PHP (rss_request.php):

<?php
    $url = $_GET["feedUrl"];
    $response = file_get_contents ($url);
    echo $response;
?> 

What's the difference? Why can't JavaScript work with both responses?

让我们在这里应用一些简单的逻辑,这在您查找原因时很有用。

你问的是差异。您给出了两个代码示例。这两个代码示例的区别是:

A: $.get("https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%3D'http%3A%2F%2Fnews.yahoo.com%2Frss%2Ftopstories'&diagnostics=false", function (data) {


B: $.get("rss_request.php?feedUrl=http://news.yahoo.com/rss/topstories", function (data) {


那么这里有什么不同呢? URL不一样!

现在你的问题是双重的,所以找到差异只是一部分,让我们回顾一下第二部分:

Why can't JavaScript work with both responses?

这隐含地指出了差异,原因是因为这两个 URL 给出了不同的数据。由于没有提供不同的数据,所以没有更多的内容可以回答你的问题。

希望回答对您有用,对您继续工作有所帮助。例如,您现在可以查看具体数据,发现即使您期望数据相同,也可以通过直接比较来了解差异。