1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| const ajax = (() => { const req = (method, url, successCallback, failureCallback, payload) => { const xhr = new XMLHttpRequest();
xhr.open(method, url); xhr.setRequestHeader("content-type", "application/json"); xhr.send(JSON.stringify(payload));
xhr.onload = () => { if (xhr.status === 200 || xhr.status === 201) { successCallback(JSON.parse(xhr.response)); } else { failureCallback(xhr.status); } }; };
return { get(url, successCallback, failureCallback) { req("GET", url, successCallback, failureCallback); }, post(url, payload, successCallback, failureCallback) { req("POST", url, successCallback, failureCallback, payload); }, patch(url, payload, successCallback, failureCallback) { req("PATCH", url, successCallback, failureCallback, payload); }, delete(url, successCallback, failureCallback) { req("DELETE", url, successCallback, failureCallback); }, }; })();
ajax.get("/todos", console.log, console.error); ajax.post( "/todos", { id: 6, content: "react", completed: false }, console.log, console.error );
|