Ajax的核心是XMLHttpRequest对象,它允许浏览器在不刷新页面的情况下与服务器通信,从而实现局部更新页面内容的效果。本文将通过几个具体的代码示例,详细介绍如何使用XMLHttpRequest对象进行GET和POST请求,并解释每个步骤的作用和注意事项。
- <!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>
- // 兼容性处理
- let xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
- console.log(xhr);
- </script>
- </body>
- </html>
-
在这段代码中,我们创建了一个XMLHttpRequest对象。为了确保兼容性,我们使用了条件判断:
通过这种方式,我们可以确保代码在不同浏览器环境下都能正常工作。
- <!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>
- // 1. 创建XMLHttpRequest对象
- let xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
-
- // 2. 与服务器建立连接
- xhr.open('get', 'http://localhost:8888/test/first', true);
-
- // 3. 发送请求
- xhr.send();
-
- // 4. 等待响应
- xhr.onreadystatechange = function () {
- if (xhr.readyState === 4 && /^(2|3)\d{2}$/.test(xhr.status)) {
- console.log(xhr.responseText);
- }
- };
- </script>
- </body>
- </html>
-
这段代码展示了如何发送一个GET请求:
- <!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>
- <input type="button" value="请求数据">
- <script>
- const btn = document.querySelector('input');
- btn.onclick = function () {
- let xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
- xhr.open('post', 'http://localhost:8888/test/fourth', true);
- xhr.onload = function () {
- console.log(JSON.parse(xhr.responseText));
- };
- xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
- xhr.send('name=张三&age=18');
- };
- </script>
- </body>
- </html>
-
这段代码展示了如何发送一个POST请求:
- <!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>
- let str = '{"id": 1, "name": "苹果", "price": 30}';
- console.log(str); // 输出原始JSON字符串
-
- let obj = JSON.parse(str);
- console.log(obj); // 输出解析后的对象
-
- obj.price = 50; // 修改价格
-
- str = JSON.stringify(obj);
- console.log(str); // 输出修改后的JSON字符串
- </script>
- </body>
- </html>
-
这段代码展示了如何处理JSON数据:
- <!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>
- // 异步请求
- let xhrAsync = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
- xhrAsync.open('get', 'http://localhost:8888/test/second', true);
- xhrAsync.onload = function () {
- console.log(JSON.parse(xhrAsync.responseText));
- };
- xhrAsync.send();
-
- // 同步请求
- let xhrSync = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
- xhrSync.open('get', 'http://localhost:8888/test/second', false);
- xhrSync.send();
- console.log(JSON.parse(xhrSync.responseText));
- </script>
- </body>
- </html>
-
这段代码展示了同步和异步请求的区别:
需要注意的是,同步请求会导致页面卡顿,通常不推荐使用,除非有特殊需求。
- <!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>
- <form action="http://www.baidu.com" method="post">
- <label for="">
- 请输入姓名:
- <input type="text" name="userName">
- </label>
- <label for="">
- 请输入密码:
- <input type="password" name="password">
- </label>
- <p><input type="submit" value="注册"></p>
- </form>
- <script>
- const form = document.querySelector('form');
- form.addEventListener('submit', function (event) {
- event.preventDefault(); // 阻止默认提交行为
-
- let xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
- xhr.open('post', 'http://localhost:8888/test/register', true);
- xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
- xhr.onload = function () {
- console.log(JSON.parse(xhr.responseText));
- };
- xhr.send(`userName=${form.userName.value}&password=${form.password.value}`);
- });
- </script>
- </body>
- </html>
-
这段代码展示了如何将表单提交与AJAX结合:
通过上述代码示例,我们详细介绍了如何使用XMLHttpRequest对象进行GET和POST请求、处理JSON数据、以及同步与异步请求的区别。这些技术点在实际开发中非常常用,掌握它们可以帮助开发者构建更加高效和响应迅速的Web应用。