发布时间:2026-10-03 03:37:01 浏览次数:4
当我们做网页开发的时候,经常需要通过 Ajax 技术来实现异步请求与响应。在这里,我将为大家讲解 Ajax 的简单使用实例代码,帮助大家更好地理解这项技术。
Ajax 的基本语法如下:
let xhr = new XMLHttpRequest(); // 创建XMLHttpRequest对象xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { // 当readyState为4且status为200时,表示响应成功,进行数据处理 let data = xhr.responseText; // 对返回的数据进行处理 }};xhr.open('GET', 'http://example.com/data', true); // 打开一个异步请求xhr.send(); // 发送请求下面是一个简单的示例,它通过 Ajax 技术请求天气 API 并获取数据:
let xhr = new XMLHttpRequest();xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { let data = JSON.parse(xhr.responseText); // 解析返回的 JSON 数据 console.log(`当前城市:${data.city}`); console.log(`当前温度:${data.temp}`); }};xhr.open('GET', 'http://api.example.com/weather?city=beijing', true);xhr.send();在这个示例中,我们创建了一个 XMLHttpRequest 对象并设置了 onreadystatechange 回调函数。当请求返回时,我们对其进行解析并处理数据,最后打印出当前城市和温度。
下面是另一个示例,它演示了如何通过 Ajax 技术提交表单数据:
<form id="myForm"> <label for="username">用户名:</label> <input type="text" id="username" name="username"><br> <label for="password">密码:</label> <input type="password" id="password" name="password"><br> <button type="button" onclick="submitForm()">提交</button></form>function submitForm() { let xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { let data = JSON.parse(xhr.responseText); if (data.success == true) { alert('登录成功!'); } else { alert('登录失败!'); } } }; xhr.open('POST', 'http://api.example.com/login', true); xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); let formData = new FormData(document.getElementById('myForm')); xhr.send(formData);}在这个示例中,我们为表单定义了一个 id,然后通过 JavaScript 获取表单数据,并将其发送到服务器端。注意,我们需要将 Content-type 设置为 application/x-www-form-urlencoded,而在发送请求时还需将表单数据转换为 FormData 对象。
通过以上两个例子,我们可以看到 Ajax 的简单实用实例代码的详细攻略。需要注意的是,在实际开发中,我们需要具体分析实际情况来选择最合适的方式进行应用。