gpt4 book ai didi

javascript - 向 OneSignal 推送通知发送 POST 请求

转载 作者:行者123 更新时间:2023-11-30 14:22:52 25 4
gpt4 key购买 nike

我有一个移动应用程序需要使用 OneSignal API 通过 POST 接收通知。我在 Postman 上测试它,一切都很顺利。现在我想要做的是:获取一个 javaScript 片段并使用 OneSignal API 向我的手机发送任何推送通知。现在我正在尝试使用 w3Schools 上的示例来完成它,但它似乎不起作用。这就是我尝试这样做的方式:

<button type="button" onclick="loadDoc()">Request data</button>

<p id="demo"></p>

<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("POST", "https://onesignal.com/api/v1/notification", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.setRequestHeader("Authorization", "Basic xxxxxxxxxxxxxxxxxx");
xhttp.send({
"app_id" : "xxxxxxxxxxxxxxxxxxxxxxxxxx",
"contents": {"en": "Hello World!"} ,
"included_segments" : ["All"]
});
}
</script>

</body>
</html>

我真的不明白我应该怎么做。

最佳答案

如今,Fetch API优于 XHR。它与浏览器一起提供,并且有轻量级的 polyfills。

const handleAsText = response => response.text();

const demo = document.getElementById("demo");

const displayResponse = responseText => demo.textContent = responseText;

function loadDoc() {
const method = "POST";
const headers = {
"Content-type": "application/json",
"Authorization": "Basic xxxxxxxxxxxxxxxxxx",
}

const body = JSON.stringify({
"app_id" : "xxxxxxxxxxxxxxxxxxxxxxxxxx",
"contents": {"en": "Hello World!"} ,
"included_segments" : ["All"],
})

return fetch("https://onesignal.com/api/v1/notification", {method, headers, body})
.then(handleAsText)
.then(displayResponse);
}

关于javascript - 向 OneSignal 推送通知发送 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52453065/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com