成功提交表单后,通过Javascript从Lambda显示消息

时间:2019-11-18 18:01:43

标签: javascript python amazon-web-services aws-lambda aws-api-gateway

我正在使用this code向我的无服务器网站(位于S3上)添加联系表单。成功发送电子邮件后,Lambda实例将返回消息"Thank you! You can download the sample here: <a href='https://someurl.com'>Download</a>"。我想向提交表单的用户显示该消息,但我不知道该怎么做。当前,我的javascript根据来自AWS API Gateway的响应代码显示硬编码的消息。但我不想在javascript中包含下载网址,因为我不希望用户无需先通过表单进行注册即可看到下载内容。

是否可以获取Lambda实例返回的字符串并将其传递回响应主体,然后通过javascript将消息显示给用户?

我当前的jQuery javascript形式:

    ! function($) {
    "use strict";
    $("form", ".contact-form ").submit(function(t) {
        t.preventDefault();
        var r = !0,
            s = this,
            e = $(s).siblings(".contact-form-result"),
            o;
        // Escape if the honeypot has been filled
        if (!!$("#whatname").val()) return;
        if ($(s).find(":required").each(function() {
                $(this).css("border-color", ""), $.trim($(this).val()) || ($(this).css("border-color", "red"), r = !1);
                var t = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
                "email" != $(this).attr("type") || t.test($.trim($(this).val())) || ($(this).css("border-color", "red"), r = !1)
            }).keyup(function() {
                $(this).css("border-color", "")
            }).change(function() {
                $(this).css("border-color", "")
            }), r) {
            //var c = $(this).serialize();
            var firstname = $("#name-input").val();
            var lastname = $("#lastname-input").val();
            var mobile = $("#mobile-input").val();
            var email = $("#email-input").val();
            var message = $("#message-input").val();
            var data = {
               firstname : firstname,
               lastname : lastname,
               mobile : mobile,
               email : email,
               message : message }
            $.ajax({
                url: "PATH-TO-AMAZON-API",
                type: "post",
                dataType: "json",
                crossDomain: "true",
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify(data),

                beforeSend: function(data) {
                    $('#submit-mail').attr('disabled', true);
                    //$('#status').html('<i class="fa fa-refresh fa-spin"></i> Sending Mail...').show();
                    o = '<p class="form-message form-success">Sending...</p>';
                    e.removeClass("hidden").html(o)
                },

                success: function (data) {
                    // clear form and show a success message
                    //alert("Successfull");
                    o = '<p class="form-message form-success">Thank you for your message!</p>';
                    e.removeClass("hidden").html(o)
                    $(s)[0].reset();
                    setTimeout(function() {
                        e.addClass("hidden").html("")
                    }, 5e3);
                    $('#submit-mail').removeProp('disabled');
                  },
                error: function (jqXHR, textStatus, errorThrown) {
                    // show an error message
                    //alert("UnSuccessfull");
                    o = '<p class="form-message form-error">Sorry, there was an error. Please try again later.</p>';
                    e.removeClass("hidden").html(o)
                    setTimeout(function() {
                        e.addClass("hidden").html("")
                    }, 5e3);
                    $('#submit-mail').removeProp('disabled');
                  }
                });

        }
    })
}(jQuery);

还有我的Python Lambda函数(使用API​​,SES和Dynamo [当前未使用Dynamo]):

import boto3
from botocore.exceptions import ClientError
import json
import os
import time
import uuid
import decimal

client = boto3.client('ses')
sender = os.environ['SENDER_EMAIL']
subject = os.environ['EMAIL_SUBJECT']
configset = os.environ['CONFIG_SET']
charset = 'UTF-8'

dynamodb = boto3.resource('dynamodb')
recipient = 'example@email.com'
def sendMail(event, context):
    print(event)
    #Send mail for contact form
    try:
        data = event['body']
        content = 'Message from ' + data['firstname'] + ' ' + data['lastname'] + ',<br>Phone: ' + data['mobile'] + ',<br>Message Contents: ' + data['message']
        #saveToDynamoDB(data)
        response = sendMailToUser(data, content)
    except ClientError as e:
        print(e.response['Error']['Message'])
    else:
        print("Email sent! Message Id:"),
        print(response['MessageId'])
    return "Thank you! You can download the sample here: <a href='https://someurl.com'>Download</a>"

def list(event, context):
    table = dynamodb.Table(os.environ['DYNAMODB_TABLE'])

    # fetch all records from database
    result = table.scan()

    #return response
    return {
        "statusCode": 200,
        "body": result['Items']
    }

def saveToDynamoDB(data):
    timestamp = int(time.time() * 1000)
    # Insert details into DynamoDB Table
    table = dynamodb.Table(os.environ['DYNAMODB_TABLE'])
    item = {
        'id': str(uuid.uuid1()),
        'firstname': data['firstname'],
        'lastname': data['lastname'],
        'email': data['email'],
        'message': data['message'],
        'createdAt': timestamp,
        'updatedAt': timestamp
    }
    table.put_item(Item=item)
    return

def sendMailToUser(data, content):
    # Send Email using SES
    return client.send_email(
        Source=sender,
        ReplyToAddresses=[ data['email'] ],
        Destination={
            'ToAddresses': [
                recipient,
            ],
        },
        Message={
            'Subject': {
                'Charset': charset,
                'Data': subject
            },
            'Body': {
                'Html': {
                    'Charset': charset,
                    'Data': content
                },
                'Text': {
                    'Charset': charset,
                    'Data': content
                }
            }
        }
    )

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

好吧,这很容易...毕竟在网上搜索了好几天才试图弄清楚这一点。原来消息就在success: function (data)中,所以我要做的就是在我的JavaScript中返回data变量。所以看起来像这样:

        success: function (data) {
            // clear form and show a success message
            //alert("Successfull");
            o = '<p class="form-message form-success">' + data + '</p>';
            e.removeClass("hidden").html(o)
            $(s)[0].reset();
            setTimeout(function() {
                e.addClass("hidden").html("")
            }, 5e3);
            $('#submit-mail').removeProp('disabled');
          },