LoginSignup
5
4

More than 5 years have passed since last update.

javascriptで生Ajax

Last updated at Posted at 2012-03-08

HTTP GET/POST だけのためにライブラリ使うのはオーバーという場合に。
(古いブラウザまでは対応していない)

// Usage:
// httpRequest( url, {
//     type: method name,
//     success: callback (optional),
//     data: map of params (optional),
// } );

function httpRequest (url, opt) {
    function throwExeption () {
        throw new Error('Usage: httpRequest(url, { type: method [, success: cb, data: params ] })');
    }
    if (!opt) throwExeption();
    var params = opt.data;
    var cb     = opt.success;
    var method = opt.type;
    if (!method) throwExeption();

    var req = new XMLHttpRequest();
    req.open(method, url, true);
    req.onreadystatechange = function() {
        if (req.readyState === 4) {
            if (req.status === 200) {
                if (cb) cb(req.responseText);
            } else {
                throw new Error("fetch failed: (" + req.status + ") " + url);
            }
        }
    };
    if (/post/i.test(method)) {
        req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        var data = '';
        for (var name in params) if (params.hasOwnProperty(name)) {
            data += encodeURIComponent(name) + "=" + encodeURIComponent(params[name]) + "&";
        }
        req.send(data);
    } else {
        req.send(null);
    }
}

5
4
0

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