<!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>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。