Created
September 28, 2016 08:08
-
-
Save jrainlau/e1491ad0a6cd09dff0f88664958ef6b8 to your computer and use it in GitHub Desktop.
ajax module
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 发送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