首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从静态html网页表单发送javascript https post或webhook?

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

Stack Overflow用户
提问于 2019-11-03 04:27:41
回答 1查看 3.4K关注 0票数 2

我有一个带有表单的静态HTML网页。填写完表单后,我想让submit按钮将http post发送到其他地方的webhook进行处理。

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

这种事情有可能发生吗?

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

这就是我到目前为止所拥有的,如果可能的话,但webhook从未收到过。所以有些事情是不正确的,或者不是我想的那样,也是不可行的:

代码语言:javascript
复制
<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()" />
EN

回答 1

Stack Overflow用户

发布于 2019-11-06 14:50:01

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

但是你可以用CORS configed从一个静态的html调用Azure函数。这是我使用c#的http触发函数代码:

代码语言:javascript
复制
#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的代码:

代码语言:javascript
复制
<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数据已经发布。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58675015

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档