3.使用XMLHttpRequest简单封装一个请求函数,支持jsonp请求和正常请求
时间: 2024-05-29 18:11:16 浏览: 75
原生JS发送异步数据请求
function request(options) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var response = xhr.responseText;
if (options.dataType === 'json') {
response = JSON.parse(response);
}
options.success(response);
} else {
options.error(xhr.statusText);
}
}
}
if (options.type === 'GET') {
var url = options.url;
if (options.data) {
var dataArr = [];
for (var key in options.data) {
dataArr.push(key + '=' + options.data[key]);
}
url += '?' + dataArr.join('&');
}
xhr.open('GET', url, true);
xhr.send();
} else if (options.type === 'POST') {
xhr.open('POST', options.url, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(JSON.stringify(options.data));
} else if (options.type === 'JSONP') {
var script = document.createElement('script');
var callbackName = 'jsonp_callback_' + new Date().getTime();
window[callbackName] = function(response) {
options.success(response);
script.parentNode.removeChild(script);
delete window[callbackName];
};
var url = options.url + '?callback=' + callbackName;
if (options.data) {
for (var key in options.data) {
url += '&' + key + '=' + options.data[key];
}
}
script.src = url;
document.body.appendChild(script);
}
}
阅读全文