JavaScript (HTML5): Ajax

JavaScript: API.js

var API = function() {
    
};
// 仮 API
API.TYPE_CREATE_USER = '/api/create';
API.TYPE_GET_USER_DATA = '/api/show';
// GET で呼び出す場合
API.prototype.get = function(url, onSuccess, onError) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url);
    xhr.onreadystatechange = function (r) {
        if (xhr.readyState == 4) {
            if (xhr.status == 0 || xhr.status == 304 || xhr.status == 200 || xhr.status == 201) {
                onSuccess(xhr.responseText, xhr);
            } else {
                onError(xhr);
            }
        }
    };
    xhr.send(null);
};
// POST で呼び出す場合
API.prototype.post = function(url,data,onSuccess,onError) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function (r) {
        if (xhr.readyState == 4) {
            if (xhr.status == 0 || xhr.status == 304 || xhr.status == 200 || xhr.status == 201) {
                onSuccess(xhr.responseText, xhr);
            } else {
                onError(xhr);
            }
        }
    };
    xhr.open('POST', url);
    xhr.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded' );
    xhr.send(this._encodeData(data));
};
API.prototype._encodeData = function(data) {
    var params = [];
    for (var name in data) {
        var value = data[ name ];
        var param = encodeURIComponent( name ).replace( /%20/g, '+' ) + '=' + encodeURIComponent( value ).replace( /%20/g, '+' );
        params.push( param );
    }
    return params.join( '&' );
};

 

呼び出し側

var apiUser = new API();
apiUser.get(API.TYPE_GET_USER_DATA, function(data, xhr) {
    var id = parseInt(JSON.parse(data)['id'], 10);
}, function(xhr) {
/*  console.log(xhr); */
});