LoginSignup
5
4

More than 5 years have passed since last update.

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

Last updated at Posted at 2018-05-24

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();
};
5
4
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4