我有一个带有表单的静态HTML网页。填写完表单后,我想让submit按钮将http post发送到其他地方的webhook进行处理。
背后的故事是,我有一个Hugo网站,全是静态的html页面。其中一页上有一张表格。如果有人填写表单并单击提交按钮,我希望通过我为处理表单数据而设置的webhook将数据发送到Azure函数、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()" />发布于 2019-11-06 14:50:01
如果你想通过js从静态html调用webhook,恐怕现在不可能,因为Azure自动化webhook目前不支持CORS。参见user voice here。
但是你可以用CORS configed从一个静态的html调用Azure函数。这是我使用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 function =>Platform features=>CORS,用"*“启用所有的源,这样我们就可以在本地测试了:

测试结果:

如您所见,您的value1数据已经发布。
https://stackoverflow.com/questions/58675015
复制相似问题