gapi.client.load无法正常工作

时间:2012-07-11 13:11:21

标签: javascript google-api url-shortener google-api-client google-url-shortener

我有以下代码,这应该是使用google api javascript客户端的简单示例,只显示硬编码缩短网址的长格式网址:

<script>
  function appendResults(text) {
    var results = document.getElementById('results');
    results.appendChild(document.createElement('P'));
    results.appendChild(document.createTextNode(text));
  }

  function makeRequest() {

    console.log('Inside makeRequest');

    var request = gapi.client.urlshortener.url.get({
      'shortUrl': 'http://goo.gl/fbsS'
    });

    request.execute(function(response) {
      appendResults(response.longUrl);
    });
  }

  function load() {

    gapi.client.setApiKey('API_KEY');
    console.log('After attempting to set API key');
    gapi.client.load('urlshortener', 'v1', makeRequest);
    console.log('After attempting to load urlshortener');
  }
</script>
<script src="https://apis.google.com/js/client.js?onload=load"></script>

除了使用实际的API密钥而不是文本“API_KEY”。

控制台输出只是:

尝试设置API密钥后

尝试加载urlshortener后

但是我从来没有看到'inside makeRequest',它位于makeRequest函数内部,这是调用gapi.client.load的回调函数,让我相信函数不起作用(或者没有完成)

任何人都可以解释为什么会出现这种情况以及如何解决这个问题?

提前致谢。

2 个答案:

答案 0 :(得分:11)

花了几个小时来搜索问题后,我发现问题是因为我在本地计算机上运行此文件而不是在服务器上运行。

当您在chrome上运行上述代码时,您会在开发人员控制台中收到此错误“无法将邮件发送到文件://。收件人的来源为null。”

由于某种原因,javascript仅在实际服务器或XAMPP或WAMP等运行时加载。

如果有专家能够解释为什么会发生这种情况,那么学习它真的很棒。

希望这有助于像我这样的其他小说:D

答案 1 :(得分:5)

简短回答(http://code.google.com/p/google-api-javascript-client/issues/detail?id=46):

The JS Client does not currently support making requests from a file:// origin.

长答案(http://en.wikipedia.org/wiki/Same_origin_policy):

The behavior of same-origin checks and related mechanisms is not well-defined
in a number of corner cases, such as for protocols that do not have a clearly 
defined host name or port associated with their URLs (file:, data:, etc.). 

This historically caused a fair number of security problems, such as the 
generally undesirable ability of any locally stored HTML file to access all 
other files on the disk, or communicate with any site on the Internet.