将JavaScript与Google API结合使用:从列表事件中获取用户选择的输入

时间:2017-11-06 16:03:41

标签: javascript api google-calendar-api

让我先说这是一个完整的新手,所以如果这是一个明显的答案,那么我提前道歉但是在花了大约一周的搜索后我找不到任何东西。

我目前正在使用Google Calendar API设计一个应用程序,该应用程序使用JavaScript列出用户选择的特定日期的事件。我已启动并运行Google的Quickstart文档,我目前正在对其进行编辑以了解其工作原理。

基本上我已经用HTML设计了一个表单,我尝试使用JavaScript来获取元素并使用它们向google提交必要的参数。现在我只是想让它接受来自的输入数据:

<label>Date: </label>
<input type="date" id="dateFirst" name="dateFirst">

进入这里:

function listUpcomingEvents() {
            gapi.client.calendar.events.list({
                'calendarId': 'primary',
                'timeMin': (new Date()).toISOString(),
                'showDeleted': false,
                'singleEvents': true,
                'maxResults': 50,
                'orderBy': 'startTime'
            }).then(function(response) {
                var events = response.result.items;
                appendPre('Upcoming events:');

我知道它需要进入&time;部分,我可能需要分配一个&#39; timeMax&#39;同样,但我尝试了几种这样的格式

(new Date(inputDate)).toISOString()

所有这些最终都会破坏脚本。

我尝试创建一些使用getElementById方法将信息提取到listUpcomingEvents()函数的新变量,但这似乎没有帮助。这些变量如下所列:

var inputDate = document.getElementById('dateFirst');
var inputLogin = document.getElementById('myText');
var inputPassword = document.getElementById('myPwd');
var inputName = document.getElementById('senName');

我完全迷失了,在我开始工作之前,我还有很长的路要走,我还是要让它接受标签上的登录信息,但我和#39;我想尝试在仅仅从所选日期开始列出事件方面取得一些进展。

我是否走在正确的轨道上?任何输入/帮助/指导将不胜感激。提前谢谢。

您可以在下面找到完整的代码:

    <!DOCTYPE html>

<html>

<head>
    <title>Calendar Card Test</title>
    <meta charset='utf-8' />
    <link rel="stylesheet" type="text/css" href="test.css" />
</head>

<body>
    <p id="testName">JavaScript Test Calendar</p>

    <div>
        <form id="topInput">
            <fieldset>
                <legend>Text input</legend>
                <p>
                    <label>Login: </label>
                    <input type="text" id="myText" value="Login info here" />
                </p>
                <p>
                    <label>Password: </label>
                    <input type="password" id="myPwd" value="secret" />
                </p>
                <p>
                    <label>Date: </label>
                    <input type="date" id="dateFirst" name="dateFirst">
                </p>
                <p>
                    <label>Name: </label>
                    <input type="text" id="senName" value="Name" />
                </p>

            </fieldset>
        </form>
    </div>


    <!--Add buttons to initiate auth sequence and sign out-->

    <input type="submit" value="Log in" id="authorize-button">
    <input type="submit" value="Sign-Out" id="signout-button">
    <pre id="content"></pre>

    <script type="text/javascript">
        // Client ID and API key from the Developer Console
        var CLIENT_ID = 'CIENT_ID';

        // Array of API discovery doc URLs for APIs used by the this application
        var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest"];

        // Authorization scopes required by the API; multiple scopes can be
        // included, separated by spaces.
        var SCOPES = "https://www.googleapis.com/auth/calendar.readonly";

        var authorizeButton = document.getElementById('authorize-button');
        var signoutButton = document.getElementById('signout-button');

        // Set variables to get data from <input> tags
        var inputDate = document.getElementById('dateFirst');
        var inputLogin = document.getElementById('myText');
        var inputPassword = document.getElementById('myPwd');
        var inputName = document.getElementById('senName');


        /**
         *  On load, called to load the auth2 library and API client library.
         */
        function handleClientLoad() {
            gapi.load('client:auth2', initClient);
        }

        /**
         *  Initializes the API client library and sets up sign-in state
         *  listeners.
         */
        function initClient() {
            gapi.client.init({
                discoveryDocs: DISCOVERY_DOCS,
                clientId: CLIENT_ID,
                scope: SCOPES
            }).then(function() {
                // Listen for sign-in state changes.
                gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);

                // Handle the initial sign-in state.
                updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
                authorizeButton.onclick = handleAuthClick;
                signoutButton.onclick = handleSignoutClick;
            });
        }

        /**
         *  Called when the signed in status changes, to update the UI
         *  appropriately. After a sign-in, the API is called.
         */
        function updateSigninStatus(isSignedIn) {
            if (isSignedIn) {
                authorizeButton.style.display = 'none';
                signoutButton.style.display = 'block';
                listUpcomingEvents();
            } else {
                authorizeButton.style.display = 'block';
                signoutButton.style.display = 'none';
            }
        }

        /**
         *  Sign in the user upon button click.
         */
        function handleAuthClick(event) {
            gapi.auth2.getAuthInstance().signIn();
        }

        /**
         *  Sign out the user upon button click.
         */
        function handleSignoutClick(event) {
            gapi.auth2.getAuthInstance().signOut();
        }

        /**
         * Append a pre element to the body containing the given message
         * as its text node. Used to display the results of the API call.
         *
         * @param {string} message Text to be placed in pre element.
         */
        function appendPre(message) {
            var pre = document.getElementById('content');
            var textContent = document.createTextNode(message + '\n');
            pre.appendChild(textContent);
        }

        /**
         * Print the summary and start datetime/date of the next ten events in
         * the authorized user's calendar. If no events are found an
         * appropriate message is printed.
         */

        function listUpcomingEvents() {
            gapi.client.calendar.events.list({
                'calendarId': 'primary',
                'timeMin': (new Date(inputDate)).toISOString(),
                'showDeleted': false,
                'singleEvents': true,
                'maxResults': 50,
                'orderBy': 'startTime'
            }).then(function(response) {
                var events = response.result.items;
                appendPre('Upcoming events:');

                if (events.length > 0) {
                    for (i = 0; i < events.length; i++) {
                        var event = events[i];
                        var when = event.start.dateTime;
                        if (!when) {
                            when = event.start.date;
                        }
                        appendPre(event.summary + ' (' + when + ')')
                    }
                } else {
                    appendPre('No upcoming events found.');
                }
            });
        }
    </script>
    <script async defer src="https://apis.google.com/js/api.js" onload="this.onload=function(){};handleClientLoad()" onreadystatechange="if (this.readyState === 'complete') this.onload()">
    </script>
</body>

</html>

1 个答案:

答案 0 :(得分:1)

使用document.getElementById()功能,您已走上正轨。你真是太近了!

document.getElementById()返回具有该id属性的元素。文本框和文本区域元素具有value属性,该属性将从文本框中返回用户的输入。

您必须做出的改变只是:

var inputDate = document.getElementById('dateFirst').value;
var inputLogin = document.getElementById('myText').value;
var inputPassword = document.getElementById('myPwd').value;
var inputName = document.getElementById('senName').value;

Here is some further reading from w3schools