[Javascript] カンタンAjaxコード

ソースコード

function Ajax(options){ this.options = options || {} const xhr = new XMLHttpRequest() xhr.open( this.options.method || 'post', this.options.url, this.options.async ?? true) xhr.setRequestHeader( 'Content-Type', this.options.content_type || 'application/x-www-form-urlencoded' ) xhr.onload = this.loaded.bind(this) xhr.send(this.get_queries(this.options.query)) } Ajax.prototype.get_queries = function(queries){ if(!queries){return null} return Object.entries(queries).map(([key, val]) => `${encodeURIComponent(key)}=${encodeURIComponent(val)}`).join('&') } Ajax.prototype.loaded = function(e){ if(!this.options.success){return} this.options.success(e.target) }

使い方

new Ajax({ url : 'sample.json', method : 'get', success : (e => { const data = JSON.parse(e.response) console.log(data) }) })

404 not-found対応

function ajax(){ const xhr = new XMLHttpRequest() xhr.open('get' , this.file , true) xhr.setRequestHeader('Content-Type', 'text/html') xhr.onreadystatechange = (e => { if(xhr.readyState !== XMLHttpRequest.DONE){return} const status = xhr.status if (status === 0 || (status >= 200 && status < 400)) { loaded(e) } else { loaded(e) } }) xhr.send() } funtion loaded(e){ const res = e.target.response }

POSTクエリ対応

ajax(){ const query = { mode : 'search', } const xhr = new XMLHttpRequest() xhr.withCredentials = true xhr.open('POST' , 'example.php' , true) xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded") xhr.onreadystatechange = (e => { if(xhr.readyState !== XMLHttpRequest.DONE){return} const status = xhr.status if (status === 0 || (status >= 200 && status < 400)) { this.loaded(e) } else { this.options.file = 'assets/html/404.html' new Asset(this.options) } }).bind(this) const query_string = Object.entries(query).map(([key, val]) => `${encodeURIComponent(key)}=${encodeURIComponent(val)}`).join('&') xhr.send(query_string) } loaded(e){ console.log(e.target.response) }

ポイント

post送信する場合は、setRequestHeader()が、"application/x-www-form-urlencoded"となっていないと正常にデータが送れない場合があるので要注意!

簡潔に処理したい場合

ajax(){ const query = { mode : 'search', } const xhr = new XMLHttpRequest() xhr.withCredentials = true xhr.open('POST' , 'example.php' , true) xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded") xhr.onload = this.loaded.bind(this) const query_string = Object.entries(query).map(([key, val]) => `${encodeURIComponent(key)}=${encodeURIComponent(val)}`).join('&') xhr.send(query_string) } loaded(e){ console.log(e.target.response) }