gpt4 book ai didi

javascript - 如何从静态 html 网页表单发送 javascript https post 或 webhook?

转载 作者:行者123 更新时间:2023-11-28 03:25:22 24 4
gpt4 key购买 nike

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

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

这种事情可能吗?

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

这是我到目前为止所拥有的,如果可能的话,但从未收到网络钩子(Hook)。所以有些事情是不对的,或者不是我所想的并且是不可行的:

<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()" />

最佳答案

如果你想通过js从静态html调用webhook,恐怕目前还不可能,因为Azure自动化webhook目前不支持CORS。请参阅user voice here

但是您可以使用 CORS configed 从静态 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功能=>平台功能=>CORS,用“*”来封装所有源,以便我们可以在本地进行测试: enter image description here

测试结果:

enter image description here

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

关于javascript - 如何从静态 html 网页表单发送 javascript https post 或 webhook?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58675015/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com