2017-04-10 24 views
0

我已使用Google提供的教程在我的網站上實施了Google登錄。但是,我不想將配置文件信息存儲在console.log中,而是希望將其顯示在我的網頁上。這是我目前的代碼:如何更改Google登錄信息以顯示個人資料信息而不是console.log

<div class="g-signin2" data-onsuccess="onSignIn"></div> 
<script> 
    function onSignIn(googleUser) { 
     var profile = googleUser.getBasicProfile(); 
     console.log("ID: " + profile.getId()); 
     console.log('Full Name: ' + profile.getName()); 
     console.log('Given Name: ' + profile.getGivenName()); 
     console.log('Family Name: ' + profile.getFamilyName()); 
     console.log("Image URL: " + profile.getImageUrl()); 
     console.log("Email: " + profile.getEmail()); 
    }; 
</script> 

我該如何改變這種情況?

回答

1

首先,如果您還沒有這樣做,您需要從Creating a Google API Console project and client ID開始。

如果您已經這樣做了,繼續將必要的代碼嵌入到您的HTML中。首先,您必須在<head></head>標記之間添加此行,以便參考Google平臺

<script src="https://apis.google.com/js/platform.js" async defer></script> 

然後插入下面代碼<body></body>標籤之間。

<div class="g-signin2" data-onsuccess="onSignIn" data-theme="dark"></div> 

現在是時候調用函數,並將用戶數據分配給HTML。裏面添加<script></script>標籤這些行內的<body>

NOTE: You may call it from another file, but i am not going to mention it here.

<script> 
function onSignIn(googleUser) { 
    var profile = googleUser.getBasicProfile(); 
    var data = ''; 
    data += '<ul>'; 
    data += '<li><img src="' + profile.getImageUrl() + '"/></li>'; 
    data += '<li>ID: ' + profile.getId() + '</li>'; 
    data += '<li>Full Name: ' + profile.getName() + '</li>'; 
    data += '<li>Given Name: ' + profile.getGivenName() + '</li>'; 
    data += '<li>Family Name: ' + profile.getFamilyName() + '</li>'; 
    data += '<li>Email: ' + profile.getEmail() + '</li>'; 
    data += '</ul>'; 
    document.getElementsByClassName("aClassOfYourOwn")[0].innerHTML =data; 
}; 
</script> 

NOTE 2: This is only one way of handling this, as you may assign new variables, and call them anywhere you like, but this is only for starter.

現在,是時候創建一個新的div。以便您可以使用您從Google獲得的內容。因此,爲了做到這一點,請在<body>標籤內添加此行。

<div class="aClassOfYourOwn"></div> 

也許右後

<div class="g-signin2" data-onsuccess="onSignIn" data-theme="dark"></div> 

它是由你。 最後,如果您想要添加簽名選項,請在<body>標籤內添加此行。

<a href="#" onclick="signOut();">Sign out</a> 

當然而且,正如你可能已經看到了,我們並沒有宣佈一個名爲signOut()功能。所以,讓我們去宣佈它。

<script> 
function signOut() { 
    var auth2 = gapi.auth2.getAuthInstance(); 
    auth2.signOut().then(function() { 
    console.log('User signed out.'); 
    var data = 'There is no user signed in'; 
    document.getElementsByClassName("g-signin3")[0].innerHTML =data; 
    }); 
} 
</script> 

這只是爲了演示。當然向用戶顯示用戶數據是毫無意義的。但你可以用它做什麼是無限的。例如,您可以獲取ID並將用戶引導至其各自的頁面。

+0

感謝您的迴應,我剛剛嘗試過實施此解決方案,它似乎並沒有工作 –

+0

它給出的錯誤「Uncaught ReferenceError:$未定義」 –

+0

你的HTML中有JQuery嗎?如果沒有,你必須下載它,或者提供像

相關問題