<!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) { // 创建Ajax对象 var xhr = new XMLHttpRequest() // 告诉Ajax对象以什么方式向哪里发送请求 var params = '' for (var attr in options.data) { params += attr + '=' + options.data[attr] + '&' } params = params.substr(0, params.length - 1) if (options.type == 'get') { options.url = options.url + '?' + params } xhr.open(options.type, options.url); // 发送请求 if (options.type == 'post') { xhr.send(params) } else { xhr.send() } // 接收响应数据,监听获取数据后的onload事件 xhr.onload = function() { console.log(xhr.responseText) } } ajax({ type: 'get', url: 'http://localhost:3000/response', data: { name: 'zhangsan', age: 30 } }) </script> </body> </html>
<!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) {
// 创建Ajax对象
var xhr = new XMLHttpRequest()
// 告诉Ajax对象以什么方式向哪里发送请求
var params = ''
for (var attr in options.data) {
params += attr + '=' + options.data[attr] + '&'
}
params = params.substr(0, params.length - 1)
if (options.type == 'get') {
options.url = options.url + '?' + params
}
xhr.open(options.type, options.url);
// 发送请求
if (options.type == 'post') {
xhr.send(params)
} else {
xhr.send()
}
// 接收响应数据,监听获取数据后的onload事件
xhr.onload = function() {
console.log(xhr.responseText)
}
}
ajax({
type: 'get',
url: 'http://localhost:3000/response',
data: {
name: 'zhangsan',
age: 30
}
})
</script>
</body>
</html>