jsFiddleでXMLHttpRequestをテスト : JavaScript

Pocket

jsFiddleでXMLHttpRequestのGETメソッドをテストする方法。MooToolsのサンプルは下記に記載されている。
» Echo Javascript file and XHR requests — jsFiddle 0.5a2 documentation

本記事はChristian Johansen (著), 長尾高弘 (翻訳) 『テスト駆動JavaScript』 ASCIIを参考にしてライブラリを使わないでXMLHttpRequestをjsFiddleでテストする方法を記載。

XHTMLパネル

<div id="output">Add text after 3 second.</div>

JavaScriptパネル

// Christian Johansen (著), 長尾高弘 (翻訳) 『テスト駆動JavaScript』 ASCII
// 本を参考にして下記サイトで配布されているスクリプトを変更。
// http://tddjs.com/


// jsFiddleでXMLHttpRequestのPOSTメソッドを使うテスト

// 参考リンク Echo Javascript file and XHR requests
// http://doc.jsfiddle.net/use/echo.html


// 名前空間処理
var tddjs = {};
tddjs.namespace = function() {
    var object = this;
    return function(name) {
        if (typeof object[name] == "undefined") {
            object[name] = {};
        }
        return object[name];
    };
}();


// XMLHttpRequestの設定処理
(function() {
    var xhr;
    var ajax = tddjs.namespace('ajax');

    // XMLHttpRequestの候補
    var options = [
        function() {
        return new ActiveXObject('Microsoft.XMLHTTP');},
        function() {
        return new XMLHttpRequest();}
    ];

    // 機能検出を使いクロスブラウザに対応する
    // option[i]()でXMLHttpRequestの生成に成功したらajax.createに登録
    var i, l;
    for (i = 0, l = options.length; i < l; i++) {
        try {
            xhr = options&#91;i&#93;();
            ajax.create = options&#91;i&#93;;
            break;
        } catch (e) {}
    }

    // HTTPのレスポンスコードが200なら成功処理


    function requestComplete(transport, options) {
        if (transport.status == 200) {
            options.success(transport);
        }
    }


    // 公開用メソッド
    function _request(url, options) {
        if (typeof url != 'string') {
            throw new TypeError('URL should be string');
        }
        if (options.method !== 'POST') {
            throw new TypeError('method is only post');
        }
        var transport = ajax.create();
        transport.open(options.method, url, true);
        transport.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        transport.setRequestHeader('Content-Length', options.data.length);
        transport.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
        // onreadystatechangeにイベントハンドラ登録
        transport.onreadystatechange = function() {
            if (transport.readyState == 4) {
                requestComplete(transport, options);
            }
        };
        // POSTメソッドでリクエスト送信
        // sendメソッドの第一引数はkey1=value1&key2=value2...のフォーマットをした文字列
        // jsFiddle API http://doc.jsfiddle.net/use/echo.html
        transport.send(options.data);
    }
    ajax.request = _request;
}());


// 実行処理
(function() {
    var output = document.getElementById('output');
    tddjs.ajax = tddjs.namespace('ajax');
    //var data = 'html=' + encodeURIComponent('<div>あいう</div>') + '&delay=3';
    var data = {
        html: '<div> あいう </div>',
        delay: 3
    }
    // フォームデータのURLエンコーディングは
    // http://ja.wikipedia.org/wiki/URL%E3%82%A8%E3%83%B3%E3%82%B3%E3%83%BC%E3%83%89#application.2Fx-www-form-urlencoded
    var encodedata = (function formURLEncoded(obj) {
        var params = [];
        for (var key in obj) {
            var value = data[key];
            // パーセントエンコーディングの半角スペース%20を+へ置換
            var param = encodeURIComponent(key).replace(/%20/g, '+')
                      + '='
                      + encodeURIComponent(value).replace(/%20/g, '+');
            params.push(param);
        }
        return params.join('&');
    }(data))
        
    if (!output) {
        return;
    }

    function log(text) {
        if (output && typeof output.innerHTML != 'undefined') {
            output.innerHTML += text;
        } else {
            document.write(text);
        }
    }

    // 接続処理
    try {
        if (tddjs.ajax && tddjs.ajax.request) {
            tddjs.ajax.request('/echo/html/', {
                success: function(xhr) {
                    log(xhr.responseText);
                },
                data: encodedata,
                method: 'POST'
            });
        } else {
            log('Browser does not support tddjs.ajax.request');
        }
    } catch (e) {
        log('An exception occured: ' + e.message);
    }
}());



/*
Copyright (c) Copyright (c) 2010-2011, Christian Johansen
All rights reserved.

    Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

        Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
        Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
        Neither the name of the <ORGANIZATION> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

コメント

No comments yet.

コメントの投稿

改行と段落タグは自動で挿入されます。
メールアドレスは表示されません。