Skip to content

Instantly share code, notes, and snippets.

@imzhi
Created March 7, 2016 02:04
Show Gist options
  • Select an option

  • Save imzhi/ce2f50179783697594da to your computer and use it in GitHub Desktop.

Select an option

Save imzhi/ce2f50179783697594da to your computer and use it in GitHub Desktop.
简单封装的ajax请求
function ajax(opts) {
var options = {
type: opts.type || 'get',
url: opts.url,
data: opts.data || '',
success: opts.success
};
if (!options.url) {
alert('报错');
}
var r = new XMLHttpRequest(), fu = '?';
r.onreadystatechange = get_data;
if (options.type === 'get') {
options.url.indexOf('?') > -1 && (fu = '&');
r.open(options.type, options.url + fu + options.data, true);
r.send(null);
} else {
r.open(options.type, options.url, true);
options.type === 'post' && r.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
r.send(options.data);
}
function get_data() {
if (r.readyState == 4) {
if (r.status == 200) {
options.success(r.responseText);
} else {
alert('接收数据出错');
}
}
};
}
ajax({
type: 'get',
url: 'get.php',
data: 'send_get=我是get',
success: function(res) {
var o = JSON.parse(res);
alert(o.data);
}
});
ajax({
type: 'post',
url: 'post.php',
data: 'send_post=我是post',
success: function(res) {
var o = JSON.parse(res);
alert(o.data);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment