javascript - javascript获取带有URL的输入变量以执行发布到URL
问题描述
我正在尝试将不同的按钮发布到不同的网址。我不确定如何在脚本中将变量从 onlcick 获取到 var url,并且从 HTML 输入设置到该 URL 的可执行 Post。此脚本与一个已设置 url 信息的按钮一起使用。我不确定如何做到这一点。我对javascript不太了解,我复制'n'粘贴它并尝试更改它。onlickonlick
我可以做一个正常的链接。唯一的问题是去那个页面。我只需要触发一个页面并停留在当前页面上。我希望有人可以帮助我指出正确的方法或提供示例代码。我对此很陌生。太感谢了,
function sendWebhook(onlick) {
var http = new XMLHttpRequest();
var url = var.onlick;
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));
}
<input id="contact-submit" src="img/red.png" type="button" value="Living Room Light On" onclick="sendWebhook(https://link1.com')" />
<input id="contact-submit" src="img/red.png" type="button" value="Living Room Light Off" onclick="sendWebhook('https://link2.com')" />
<input id="contact-submit" src="img/red.png" type="button" value="Living Room Light Off" onclick="sendWebhook('https://link3.com')" />
解决方案
该行var url = var.onlick;
不是有效的 javascript。我将函数参数的名称更改为“url”并删除了有问题的行。
function sendWebhook(url) {
var http = new XMLHttpRequest();
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));
}
<input id="contact-submit" src="img/red.png" type="button" value="Living Room Light On"
name="https://link3.com"
onclick="sendWebhook('https://link1.com')" />
<input id="contact-submit" src="img/red.png" type="button" value="Living Room Light Off"
onclick="sendWebhook('https://link2.com')" />
<input id="contact-submit" src="img/red.png" type="button" value="Living Room Light Off"
onclick="sendWebhook('https://link3.com')" />
如果要将函数参数的值分配给新变量,请查看以下示例代码:
function aFunctionThatAssignsAParameterToAVariable(aParamter) {
var myNewVariable = aParamter;
console.log(myNewVariable);
}
aFunctionThatAssignsAParameterToAVariable("banana");
推荐阅读
- html - 跨度超出 div 且不完全适合
- windows - 编译后命令提示符更改颜色
- python - 使用 Python 使用 SELECT 语句的 SQL 中的嵌套循环
- typescript - 打字稿和处理 FileReader
- apache-kafka - 如何制作kafka主题的unqiue和去重版本
- scala - 在 Scala 中使用依赖注入模拟分发
- mysql - MySQL - 比较两个表并将它们求和
- sql - SSMS 中 NOT IN 的替代方案
- amp-html - 设置标题 AMP-Redirect-To 后,目标为 _blank 的 amp-form 应重定向?
- r - 如何从 R 中的哈希表中通过其值检索键的名称