【问题标题】:Accessing pages on Google Sites to load on my site访问 Google 协作平台上的页面以加载到我的网站上
【发布时间】:2014-03-13 17:51:46
【问题描述】:

通过 javascript (jQuery) 我正在尝试将某些页面的内容从 Google 站点加载到不同站点的页面中的元素上。使用 jQuery 的负载我得到了预期:

XMLHttpRequest cannot load https://sites.google.com/site/foo/home. No 'Access-Control-
Allow-Origin' header is present on the requested resource. Origin 'http://bar' is 
therefore not allowed access.

我尝试使用 CORS,使用下面的代码(我在 http://www.html5rocks.com/en/tutorials/cors/ 找到),但得到了相同的结果。

function createCORSRequest(method, url) {
  var xhr = new XMLHttpRequest();
  if ("withCredentials" in xhr) {
    // XHR for Chrome/Firefox/Opera/Safari.
    xhr.open(method, url, true);
  } else if (typeof XDomainRequest != "undefined") {
    // XDomainRequest for IE.
    xhr = new XDomainRequest();
    xhr.open(method, url);
  } else {
    // CORS not supported.
    xhr = null;
  }
  return xhr;
}

function makeCorsRequest() {
  var url = 'https://sites.google.com/site/edumonkihelp/test0';

  var xhr = createCORSRequest('GET', url);
  if (!xhr) {
    alert('CORS not supported');
    return;
  }

  xhr.onload = function() {return xhr.responseText;};
  xhr.onerror = function() {alert('Woops, there was an error making the request.');};
  xhr.send();
}

所以我想我有两个问题: 1. 您可以访问 Google 协作平台中页面的内容吗? 2. 还有其他类似的服务可以让您这样做吗?

谢谢!

【问题讨论】:

    标签: javascript jquery cors


    【解决方案1】:

    根据Google Sites Data API,您可以使用path 参数来获取位于http://sites.google.com/site/siteName/path/to/the/page 的特定页面:

    GET /feeds/content/domainName/siteName?path=/path/to/the/page
    

    为了使用 jQuery.ajax() 执行 Ccoss 域请求,请指定 dataType: 'jsonp'

    示例

    该示例演示如何检索位于https://sites.google.com/site/nokiaofficescontacts/hq 的页面:

    $.ajax({
        url: 'https://sites.google.com/feeds/content/site/nokiaofficescontacts?path=/hq&alt=json',
        success: function (data) { 
            console.log('Page was succesfully retrieved');
            console.log(data.feed.entry[0].title); //print Page Title
        },
        error: function (error) {
            console.log(JSON.stringify(error));
        },
        dataType: 'jsonp'
    });
    

    注意:alt=json 指定请求 JSON 格式的响应。

    【讨论】:

    • 这行得通。我应该但没有预见到的一个问题是 Google 使用了许多 css 类来格式化页面。这些自然不包含在页面的内容中。侧边栏、页眉和页脚也不会包括在内,它们不是该页面的一部分,而是网站的一部分。一切都非常合乎逻辑!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-19
    相关资源
    最近更新 更多