HTML
JavaScript
HTML,CSS,JavaScript

生のjsでgetする(jQuery禁止)

More than 1 year has passed since last update.


javascriptでjQueryなしでgetする

色々あってjqueryが嫌いになったから、生のjsで書いた

function callback(data){console.log(data)}

get('example.com',{'foo':'bar','hoge':'hoge'},callback)

function get(url, param, callback_function){

let Full_url = url + "?";
let count = 0;
for (key in param) {
if (count++ != 0) Full_url += "&";
Full_url += key + "=" + param[key]
}
let xhr = new XMLHttpRequest();
console.log(Full_url)
xhr.open('GET', Full_url);
xhr.setRequestHeader('Content-Type', 'text/html');
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
callback_function(xhr.responseText)
} else {
console.log("error\nstatus = " + xhr.status);
}
}
};
xhr.send();
};