首页 > 解决方案 > 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')" />

标签: javascriptvariablesurlpostinput

解决方案


该行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");


推荐阅读