我怎样才能通过JS代码使用oauth 2.0逐个来自gmail

时间:2016-03-04 14:57:45

标签: javascript oauth-2.0

我使用JS代码检索了gmail联系人。

<script type="text/javascript">
      var clientId = '';
      var apiKey = '';
      var scopes = 'https://www.googleapis.com/auth/contacts.readonly';
      $(document).on("click",".googleContactsButton", function(){
        gapi.client.setApiKey(apiKey);
        window.setTimeout(authorize);
      });
      function authorize() {
        gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthorization);
      }
      function handleAuthorization(authorizationResult) {
        if (authorizationResult && !authorizationResult.error) {
          $.get("https://www.google.com/m8/feeds/contacts/default/thin?alt=json&access_token=" + authorizationResult.access_token + "&max-results=500&v=3.0",
            function(response){
              //process the response here
              //console.log(response);

              var response = (JSON.stringify(response.feed.entry[1].gd$email, null, 4));
console.log(response);
            });
        }
      }
    </script>

现在我的问题是我通过传递没有抓住任何一封电子邮件。在

(JSON.stringify(response.feed.entry[1].gd$email, null, 4));
entry[0 or 1 or etc]

之后

以上代码的结果为[ { "rel": "http://schemas.google.com/g/2005#other", "address": "ashish.ascent@gmail.com", "primary": "true" } ]

我想逐个检索所有电子邮件,我该如何实现?

2 个答案:

答案 0 :(得分:0)

暂时忽略JSON.stringify(),您可以执行以下操作。

Array .map方法返回一个新数组。

var arrayOfEmails = response.feed.entry.map(function (feedEntry) {
  return feedEntry.address;
})

答案 1 :(得分:0)

我找到了解决方案

function(response){
   //console.log(response.feed.entry.length);
    for(var i = 0;i<response.feed.entry.length; i++){
    if(response.feed.entry[i].gd$email)
    {
        console.log("email is " + response.feed.entry[i].gd$email[0].address);
    }
}
});

收到回复后,使用for循环逐个打印电子邮件,直到回复有电子邮件