<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
function ajax(options) {
let xhr = new XMLHttpRequest();
let params = '';
for (var attr in options.data) {
params += attr + '=' + options.data[attr] + '&'; //截取对象形式参数
}
params = params.substr(0, params.length - 1);
if (options.type == 'get') { //get方法
options.url = options.url + '?' + params;
}
xhr.open(options.type, options.url);
if (options.type == 'post') { //post方法
let content_type = options.header.content_type;
xhr.setRequestHeader('Content-Type', content_type);//设置数据格式
if (content_type == 'application/json') {
xhr.send(JSON.stringify(options.data));
}
else {
xhr.send(params);
}
}
else {
xhr.send();
}
xhr.onload = function () {
if (xhr.status == 200) {
options.success(xhr.responseText);
} else {
options.error(xhr.responseText, xhr);
}
}
ajax({
url: 'http://localhost:3000/get',
type: 'get',
data: {
name: 'qq',
age: 21,
},
header: {
content_type: 'application/json' // 'application/x-www-form-urlencoded'
},
success: function (data) {
console.log('这是success函数' + data);
},
error: function (data, xhr) {
console.log('这是error函数' + data);
console.log(xhr);
}
});
}
</script>
</body>
</html>
你在ajax函数内调用ajax函数,是要递归吗?
在chrome里打开开发者工具,看看控制台是否有报错