有人能指出我正确的方向吗?我是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>
答案 0 :(得分: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
属性,该属性将要testId
的{{1}}保留到Webhook
我用POST
抓取了这个元素,并使用document.querySelectorAll("[data-elementor-id]")[0]
提取了ID
,然后通过字符串串联将其用于element.dataset.elementorId
请求-{{1} }。
请注意,POST
返回一个数组-在我的情况下,页面上只有一个具有"url=" + testId
属性的元素,因此我选择了第一个元素,因此选择了document.querySelectorAll
。如果页面上有更多具有相同属性的元素,而第一个元素不是具有适当ID的元素,请确保指定正确的索引,即data-elementor-id
。
希望这会有所帮助。