将帖子ID添加到AJAX请求中

问题描述 投票:0回答:1

有人能指出我正确的方向吗?我是AJAX的新手。

我想将帖子的ID添加到此简单请求中。

有人吗?谢谢马丁

<!DOCTYPE html>
<html>
<body>

<h1>Postback to webhook incl PostID</h1>

<button type="button" onclick="loadDocs()">Postback</button>

<p id="testID"></p>

<script>
function loadDocs() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("testID").innerHTML = this.responseText;
    }
  };
  xhttp.open("POST", "https://hook.integromat.com/h17qasnzptr4lo7cs6br1vmrv28t11ji", true);
  xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhttp.send("url=POSTIDHERE");
}
</script>

</body>
</html>
javascript ajax wordpress
1个回答
0
投票

这是一个基于注释中提到的有效示例:

function loadDocs() {
  var element = document.querySelectorAll("[data-elementor-id]")[0];
  var testId = element.dataset.elementorId;

  var URL =
    "https://hook.integromat.com/h17qasnzptr4lo7cs6br1vmrv28t11ji";
  var http = new XMLHttpRequest();
  var params = "url=" + testId;

  http.open("POST", URL, true);
  http.setRequestHeader(
    "Content-Type",
    "application/x-www-form-urlencoded"
  );
  http.onreadystatechange = function() {
    if (http.readyState == 4 && http.status == 200) {
      console.log("success!");
    }
  };
  http.send(params);
}
<h2>Postback to webhook incl PostID</h2>
<button type="button" onclick="loadDocs()">Postback</button>

<!-- This can be any element, but let's assume it's a DIV-->
<div data-elementor-id="228">
  <h2>228</h2>
</div>

如您所见,我有一个元素(在这种情况下为div),它具有data-elementor-id属性,该属性将要testIdPOST保存到Webhook。

[我用document.querySelectorAll("[data-elementor-id]")[0]抓取了这个元素,并使用ID提取了element.dataset.elementorId,然后我通过使用字符串串联POST将其用于"url=" + testId"请求。

[请注意,document.querySelectorAll返回一个数组-在我的情况下,页面上只有一个具有data-elementor-id属性的元素,所以我选择了第一个元素,因此是[0]。如果页面上有更多具有相同属性的元素,而第一个元素不是具有适当ID的元素,请确保指定正确的索引,即[2]

希望这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.