今時のxhrでajaxするライブラリを作った話

2022年3月13日

Javascript テクノロジー

eyecatch アジャックス?エイジャックス?言い方がどっちか迷う、ユゲタです。 ずっと以前に、自分で使う用のXMLHttpRequest処理を作った事が遠い昔のようですが、それもそのはずで、何しろInternetExplorer対応バージョンですからね。 別にIEに対応したままでもいいんですが、最近流行りのimport処理でajax機能をライブラリ化してみたくなったので、プログラミングをしてみました。 Nodejsでは、Axiosを使う事でAjax機能が実現できますが、クライアントJavascriptでは、fetchなどもでてきて便利になってきているようですが、個人的には、xhrを使い続けています。 そんな似た思考の型で、importしたライブラリでajax処理をしたい人は是非、コピってお使いください。

ソースコード

'use strict' export const ver = "0.0.1" const settings = { query : {}, // Array , Object each ok ( ex: {a:"1"} or ["a=1"] ) methid : "post", // post | get async : true, content : "application/x-www-form-urlencoded", // content-type success : function(data , options , req , res){}, error : function(data , options , req , res){}, type : "", // request-type header : "", // request-header } /** * Ajax tool * sample : * import { Ajax } from "./ajax.js" * new Ajax({ * url : "http://example.com", * query : { * a : "a" * }, * success : function(response , request){ * ... * }, * error : function(err){ * ... * } * }); */ export class Ajax{ constructor(options){ if(!options){ return } this.options = this.setOptions(options) if(!this.options.url){ return } this.setQueries() this.flow() } setOptions(options){ for(var i in settings){ options[i] = (typeof options[i] === "undefined") ? settings[i] : options[i] } return options } setQueries(){ if(!this.options || !this.options.query || typeof this.options.query !== "object"){return} this.queries = []; if(this.options.query.constructor === Array){ for(let q of this.options.query){ var sp = q.split("="); this.queries.push(sp[0]+"="+encodeURIComponent(sp.slice(1))); } } else{ for(var i in this.options.query){ this.queries.push(i+"="+encodeURIComponent(this.options.query[i])); } } } createHttpRequest = function(){ if(window.ActiveXObject){ //Win ie用 try{ return new ActiveXObject("Msxml2.XMLHTTP") //MSXML2以降用; } catch(e){ try{ return new ActiveXObject("Microsoft.XMLHTTP") //旧MSXML用; } catch(e2){return null} } } else if(window.XMLHttpRequest){ return new XMLHttpRequest() //Win ie以外のXMLHttpRequestオブジェクト実装ブラウザ用; } else{return null} } flow(){ this.req = this.createHttpRequest() if(!this.req){return} this.open() this.custom() this.header() this.req.onreadystatechange = this.readyState.bind(this) this.type() this.send(); } custom(){ } header(){ if(this.options.content){ this.req.setRequestHeader('Content-Type', this.options.content); } } open(){ this.req.open(this.options.method , this.options.url , this.options.async); } type(){ if(!this.options.type){return} this.req.responseType = this.option.type; } send(){ const queries = (!this.queries.length) ? this.queries.join("&") : null; this.req.send(queries); } readyState(res){ if (this.req.readyState==4){ //コールバック if (this.req.status === 200) { this.options.success(this.req.responseText , this.options , this.req , res); } else{ this.options.error(this.req.responseText , this.options , this.req , res); } } } }

使い方

import { Ajax } from "ajax.js" new Ajax({ url : "http://example.com/sample.txt", success : (function(data , res , req){ this.files[num] = data }).bind(this), }) ライブラリを読み込んで実際に実行する(サンプルはrun.jsというファイル名で実行しています)jsに上記のように記述する事で、urlからデータを取得することができます。 APIバックエンドサーバーなどと繋ぎ合わせる事で、非常に簡易に便利に、手軽に、jsとサーバーサイドを繋ぐ事ができますよ。

最後に

プログラムを作ってみて、ひとつ大きな矛盾に気がつきました。 今回対応したimport機能は、IEは未対応の機能なのに、作ったプログラムは、IEの場合の分岐が存在します。 この処理いらんですよね。 if文が1個なくなるだけですが、こういう無駄を排除するのも、設計においては重要な要素なので、そのうちに直しておきたいと思います。 このままの記述でも正常に動作するので、気になる人は、ご自身で削除してお使いください。 え?「お前がすぐに直せや!」ですって? そのような注文はGithubのプルリクでお願いします。 ※これまだ、githubにpushしてませんけどね・・・orz

人気の投稿

このブログを検索

ごあいさつ

このWebサイトは、独自思考で我が道を行くユゲタの少し尖った思考のTechブログです。 毎日興味がどんどん切り替わるので、テーマはマルチになっています。 もしかしたらアイデアに困っている人の助けになるかもしれません。

ブログ アーカイブ