如何从这段代码中删除jQuery?

时间:2018-05-07 04:35:21

标签: javascript jquery webhooks

由于某种原因,我不想在此JavaScript代码中使用jQuery:

$(function() {
  var url = ; //webhook URL here
  var content = "Hiii";
  var username = "Hi";
  $.post(url, {"content": content, "username": username});
  });

有没有办法将其转换为不需要jQuery的代码?

2 个答案:

答案 0 :(得分:2)

首先,你可以用{/ p>之类的东西替换$()

document.addEventListener('DOMContentLoaded', (e) => {})

其次,如果您只定位到较新的浏览器,则可以使用fetch

document.addEventListener('DOMContentLoaded', (e) => {
    var url = ; //webhook URL here
    var content = "Hiii";
    var username = "Hi";
    fetch(url, {
        method: 'POST',
        body: JSON.stringify({
            content: content,
            username: username,
        })
    });
});

或回退使用普通XHR

var oReq = new XMLHttpRequest();
oReq.open("POST", url, true);
oReq.send({
        content: content,
        username: username,
});

答案 1 :(得分:1)

var content = "Hiii";
var username = "Hi";
var http = new XMLHttpRequest();
var url = "your API url";
http.open("POST", url, true);

//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

http.onreadystatechange = function() {//Call a function when the state changes.
    if(http.readyState == 4 && http.status == 200) {
        alert(http.responseText);
    }
}
http.send({"content": content, "username": username});

您可以使用XMLHttpRequest来执行上面的AJAX调用。