17
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

自力でAjax通信してみる

Last updated at Posted at 2014-03-18

実装

var Ajax = {
    endpoint: "/",
    get : function(path, callback, param, header) {
        return this.request("GET", this.endpoint + path, callback, param, header);
    },
    post : function(path, callback, param, header) {
        return this.request("POST", this.endpoint + path, callback, param, header);
    },
    request : function(method, url, callback, param, header) {
        var xhr = this.xhr();
        xhr.open(method, url, true);
        xhr.onreadystatechange = function() {
            if(xhr.readyState == 4) {
                if(xhr.status == 200) {
                    var text = xhr.responseText;
                    var type = xhr.getResponseHeader("Content-Type");
                    if(type.indexOf("application/json") == -1) {
                        callback(text);
                    } else {
                        var js_obj;
                        if(JSON.parse) {
                            js_obj = JSON.parse(text);
                        } else {
                            js_obj = eval("(" + text + ")");
                        }
                        callback(js_obj);
                    }
                }
                xhr = null;
            }
        }
        if(header) {
            for(var key in header) {
                var value = header[key];
                xhr.setRequestHeader(key, value);
            }
        }
        if(param) {
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            var lines = [];
            var i = 0;
            for(var key in param) {
                var value = param[key];
                lines[i] = key + "=" + encodeURIComponent(value);
                ++i;
            }
            xhr.send(lines.join("&"));
        } else {
            xhr.send("");
        }
    },
    xhr : function() {
        if (window.XMLHttpRequest) {
            return new XMLHttpRequest();
        } else {
            try {
                return new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                return new ActiveXObject("Microsoft.XMLHTTP");
            }
        }
    }
} 

実行結果

Ajax.get('path/to/api', function(x){ console.log(x); });
// => サーバからのレスポンスはContent-Typeに「application/json」が指定されていれば、
//    レスポンス本文を解析してオジェクト(連想配列や配列)になって変数「x」に格納される

まとめ

Ajax通信はjQueryとかを使うのが王道なのですが、自分で実装してみても以外と簡単。

17
17
2

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
17
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?