admin管理员组

文章数量:1400286

How do I write this peace of Ajax call that is written in jQuery, pletely in vanilla JavaScript

What should be converted into vanilla javascript

$.ajax({
	type: "DELETE",
url: "/users/delete/" + $(".deleteUser").data('id');
}}

How do I write this peace of Ajax call that is written in jQuery, pletely in vanilla JavaScript

What should be converted into vanilla javascript

$.ajax({
	type: "DELETE",
url: "/users/delete/" + $(".deleteUser").data('id');
}}

What I think it should be, but the console log gave me the following error message : request is not defined. And I am afraid it would not pick up the id.

request.open("DELETE", "/users/delete/" + this.dataSet('id')); 

Share Improve this question asked Oct 27, 2017 at 19:43 Frontend employeeFrontend employee 7392 gold badges13 silver badges26 bronze badges 1
  • 1 stackoverflow./questions/8567114/… – tymeJV Commented Oct 27, 2017 at 19:46
Add a ment  | 

3 Answers 3

Reset to default 4

You can't get any more vanilla then good old xmlhttprequest.

var xhr1 = new XMLHttpRequest();
xhr1.open('DELETE', "http://127.0.0.1:80/users/delete/", true);
xhr1.onreadystatechange = function() {
    if (this.status == 200 && this.readyState == 4) {

        dostuff = this.responseText;
  };//end onreadystate
 xhr1.send();

Enjoy.

You can simply use the new fetch API:

fetch(url, { method: 'DELETE' })
    .then((res)=>{
        res.json()
        window.location.href = '/'
    });

request is node module, it is not available in browser (altho there is a fork for browser, still it is not vanilla JS, but a library instead).

If you are fine with not supporting IE (just IE, edge should be fine), you can use fetch API:

fetch("/users/delete/" + $(".deleteUser").data('id'), {
    method: "DELETE",
}}.then(function (response) {
    console.log(response);
});

https://developer.mozilla/en-US/docs/Web/API/Fetch_API

Btw I guess you also want to get rid of the $.data call, this is vanilla JS version:

var id = document.querySelector('.deleteUser').getAttribute('data-id');

本文标签: How to write Ajax call delete method with specific id in vanilla javascriptStack Overflow