Skip to content

Instantly share code, notes, and snippets.

@jrainlau
Created September 28, 2016 08:08
Show Gist options
  • Save jrainlau/e1491ad0a6cd09dff0f88664958ef6b8 to your computer and use it in GitHub Desktop.
Save jrainlau/e1491ad0a6cd09dff0f88664958ef6b8 to your computer and use it in GitHub Desktop.
ajax module
/**
* 发送ajax请求,允许传入一个配置对象和一个回调函数
*
* @param {Object} config 配置对象
* 举例:var config = {
method: 'GET',
url: 'url',
params: {number: 1, price: 10},
async: true
}
* @param {Function} cb 回调函数
*
*/
function ajax (config, cb) {
var xhttp = new XMLHttpRequest()
var method = config.method
var url = config.url
var params = JSON.stringify(config.params)
var async = config.async
if (method === 'POST') {
xhttp.open('POST', url, async)
xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8')
xhttp.send('info=' + params)
} else if (method === 'GET') {
url += '?' + 'info=' + params
xhttp.open('GET', url, async)
xhttp.send()
}
xhttp.onreadystatechange = function () {
if (xhttp.readyState === 4 && xhttp.status === 200) {
var data = xhttp.responseText
cb(data)
}
}
}
module.exports = ajax;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment