このブログの更新は Twitterアカウント @m_hiyama で通知されます。
Follow @m_hiyama

メールでのご連絡は hiyama{at}chimaira{dot}org まで。

はじめてのメールはスパムと判定されることがあります。最初は、信頼されているドメインから差し障りのない文面を送っていただけると、スパムと判定されにくいと思います。

参照用 記事

最近のブラウザは、ネイティブJSONサポートがあるんだね

JSONをデータとしたAjax通信の実験をしようと思ったのですが、Ajax通信以外に何もやらないので、Ajaxのみのライブラリを探してみました。
すこし古め(2010年11月)の情報ですが次の記事を見つけました。

ここで紹介されている microajax - Tiny AJAX library はほんとに小さいライブラリです。それを僕が膨らませてしまったのが下に貼り付けたソースです。若干読みやすくしたのと、ネイティブJSONサポートを使ってみたところが変更点です。

JavaScriptで書かれたJSON処理ライブラリがいくつかありますが、今ではブラウ自身が JSON.parse(text) と JSON.stringify(data) をサポートしています。古いブラウザへの考慮が不要なら、ネイティブJSONを使うとスッキリしますね。

この下にソース:

/* microajax-m.js -- Modified Microajax -*- coding: utf-8 -*- */

/* microAjax (https://code.google.com/p/microajax/) Original Copyright */
/*
Copyright (c) 2008 Stefan Lange-Hegermann

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

/*

readyStateの値:

0 = uninitialized(読み込み開始前の初期状態)
1 = loading(読み込み中)
2 = loaded(読み込んだ)
3 = interactive(読み込んだデータを解析中)
4 = complete(読み込んだデータの解析完了、または失敗した。つまり処理が終わった)

*/

if (! this.microajax) {
  microajax = {};
};

microajax.bindFunctionToObject = function(func, obj) {
  return function (/* arguments */) {
    return func.apply(obj, arguments);
  };
};


// microajaxの callback はテキスト引数を1つ取る。これを3つにした。
// 
// 1. status (整数値)
// 2. responseText 
// 3. XmlHttpRequest (オブジェクト自身)


microajax.getXHR = function() {
  if (window.ActiveXObject) {
    return new ActiveXObject('Microsoft.XMLHTTP');
  } else if (window.XMLHttpRequest){
    return new XMLHttpRequest();    
  } else {
    return false;    
  }
};

microajax.Requester = function(url, defaultCallback_) {
  this.url = url;
  this.xhr = microajax.getXHR();
  if (!this.xhr) {
    throw new Error("no XmlHttpObject");
  }
  this.defaultCallback = 
    defaultCallback_ ? defaultCallback_ : microajax.Requester.defaultCallback;
  this.callback = this.defaultCallback;

  this.stateChange = function (object) {
    if (this.xhr.readyState === 4) {
      this.callback(this.xhr.status, this.xhr.responseText, this.xhr);
    }
  };
};

microajax.Requester.defaultCallback = function(status, text, xhr) {
  var s = '' + status + ' ' + xhr.statusText + '\n';
  if (text.length < 80) {
    s += text;
  } else {
    s += text.substring(0, 80) + " ...";
  }
//  s += '\n' + xhr.getAllResponseHeaders();
  alert(s);
};

microajax.Requester.defaultJsonReceiver = function(text) {
//  alert(text);
  var data = JSON.parse(text);
  console.debug(data);
};

microajax.Requester.prototype.setCallback = function(callback) {
  this.callback = callback;
};

microajax.Requester.prototype.setUrl = function(url) {
  this.url = url;
};

microajax.Requester.prototype.send = function(method, url_, body_, contentType_, callback_) {
  var req = {
    url: url_ ? url_ : this.url,
    xhr: this.xhr,
    callback: callback_ ? callback_ : this.callback
  };
  if (!req.url) {
    throw new Error("url is not specified");
  }
  req.xhr.onreadystatechange = microajax.bindFunctionToObject(this.stateChange, req);
  if (method === 'GET') {
    req.xhr.open("GET", req.url, true);
  } else if (method === 'POST') {
    var body = body_ ? body_ : "";
    var contentType = contentType_ ? contentType_  : 'application/json; charset=utf-8';
    req.xhr.open("POST", req.url, true);
    req.xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    req.xhr.setRequestHeader('Content-type', contentType);
    req.xhr.setRequestHeader('Connection', 'close');
  } else {
    throw new Error("bad HTTP method name");
  }
  req.xhr.send(body);
};


microajax.Requester.prototype.getText = function(url_, callback_) {
  // args: method, url_, body_, contentType_, callback_ 
  this.send('GET', url_, null, null, callback_);
};

microajax.Requester.prototype.getDataViaJson = function(url_, callback_) {
  // args: method, url_, body_, contentType_, callback_ 
  var callback = callback_ ? callback_ : microajax.Requester.defaultJsonReceiver;
  this.send('GET', url_, null,  null, callback);
};

microajax.Requester.prototype.postDataViaJson = function(url_, data, callback_) {
  var body = JSON.stringify(data);
  // args: method, url_, body_, contentType_, callback_ 
  this.send('POST', url_, body, null, callback_);
};