首页 > 解决方案 > 如何从静态 html 网页表单发送 javascript https 帖子或 webhook?

问题描述

我有一个带有表单的静态 HTML 网页。填写表格后,我希望提交按钮将 http 帖子发送到其他地方的 webhook 进行处理。

这背后的故事是我有 Hugo 网站,它都是静态的 html 页面。其中一页上有一张表格。如果有人填写该表单并单击提交按钮,我希望通过我设置的处理表单数据的 webhook 将该数据发送到 Azure Function、Azure Runbook 等。

这种事情可能吗?

请注意,Hugo 网站托管在 PHP 或任何服务器端处理等不可用的存储上。这就是为什么我正在寻找另一种方式。如果可能的话,我唯一的想法是客户端 javascript,但我对 Javascript 不是很好。

这就是我到目前为止所拥有的,如果可能的话,但从未收到过 webhook。所以有些事情是不对的,或者不是我认为的并且不可行:

<script>
function sendWebhook() {
    var content = {"value1" : "test data"};
    var url = "https://s16events.azure-automation.net/webhooks?token=<myToken>";
    var options =  {
    "method" : "post",
    "contentType" : "application/json",
    "payload" : JSON.stringify(content)
};
return UrlFetchApp.fetch(url, options);
}
</script>
<input id="contact-submit" type="button" class="btn btn-transparent" value="Submit" onclick="sendWebhook()" />

标签: javascripthtmlformsazurehugo

解决方案


如果你想通过 js 从静态 html 调用 webhook,恐怕目前是不可能的,因为 Azure 自动化 webhook 目前不支持 CORS。在此处查看用户声音

但是您可以从配置了CORS的静态 html 调用 Azure Function 。这是我使用 c# 触发的 http 函数代码:

#r "Newtonsoft.Json"

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;

public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");

    string value1 = req.Query["value1"];

    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
    dynamic data = JsonConvert.DeserializeObject(requestBody);
    value1 = value1 ?? data?.value1;

    return value1 != null
        ? (ActionResult)new OkObjectResult($"Hello, {value1}")
        : new BadRequestObjectResult("Please pass a value1 on the query string or in the request body");
}

它会在您的 html 中回复您“value1”的值。

这是 html 的代码:

<script>
function sendWebhook() {

    var http = new XMLHttpRequest();
    var url = '<URL OF YOUR AZURE FUNCTION>';
    var content = {"value1" : "test data"};
    http.open('POST', url, true);

    //Send the proper header information along with the request
    http.setRequestHeader('Content-type', 'application/json');

    http.onreadystatechange = function() {//Call a function when the state changes.
        if(http.readyState == 4 && http.status == 200) {
            alert(http.responseText);
        }
    }
    http.send(JSON.stringify(content));

}
</script>


<input id="contact-submit" type="button" class="btn btn-transparent" value="Submit" onclick="sendWebhook()" />

让我们转到您的 Azure 函数 =>Platform features=>CORS 以使用“*”启用所有 Origin,以便我们可以在本地进行测试: 在此处输入图像描述

测试结果 :

在此处输入图像描述

如您所见,您的 value1 数据已发布。


推荐阅读