<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> function ajax(options) { var defaults = { type: 'get', url: 'http://localhost:3000/response', data: {}, header: { 'Content-Type': 'application/x-www-form-urlencoded' }, success: function() {}, error: function() {} } Object.assign(defaults, options) // 创建Ajax对象 var xhr = new XMLHttpRequest() // 告诉Ajax对象以什么方式向哪里发送请求 var params = '' for (var attr in defaults.data) { params += attr + '=' + defaults.data[attr] + '&' } params = params.substr(0, params.length - 1) if (defaults.type == 'get') { defaults.url = defaults.url + '?' + params } xhr.open(defaults.type, defaults.url); // 发送请求 if (defaults.type == 'post') { // 用户希望像服务器端传递的请求参数类型 var contentType = defaults.header['Content-Type'] // 设置请求参数类型,这个非常重要哦 xhr.setRequestHeader('Content-Type', contentType) // 如果传递json数据类型,那么就需要传递json数据 if (contentType == 'application/json') { xhr.send(JSON.stringify(defaults.data)) } else { xhr.send(params) } } else { xhr.send() } // 接收响应数据,监听获取数据后的onload事件 xhr.onload = function() { var contentType = xhr.getResponseHeader('Content-Type') var responseText = xhr.responseText if (contentType.includes('application/json')) { responseText = JSON.parse(xhr.responseText); } if (xhr.status == 200) { defaults.success(xhr.responseText, xhr) } else { defaults.error(xhr.responseText, xhr) } } xhr.onerror = function() { alert('网络出现问题') } } ajax({ type: 'post', url: 'http://localhost:3000/response', data: { name: 'zhangsan', age: 30 }, success: function(data, xhr) { console.log('这是一个success函数' + data) }, error: function(data, xhr) { console.log('这是一个error函数' + data) } }) </script> </body> </html>