在现代网页开发中,AJAX(Asynchronous JavaScript and XML)技术被广泛应用于实现异步请求,以便无需重新加载页面即可更新内容。下面我们展示如何用纯 JavaScript 实现 AJAX 请求。
1. 基本的 AJAX 请求
//language:js
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
document.getElementById("demo").innerHTML = this.responseText;
}
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
在这个例子中,我们创建了一个新的 XMLHttpRequest
对象,并通过 open
方法指定请求类型(GET)、请求的 URL(”ajax_info.txt”)以及是否异步(true)。当请求成功完成后,onload
事件会被触发,响应的内容会被显示在页面上的 demo
元素中。
2. 发送表单数据并响应
如果我们需要发送表单数据,可以使用 FormData
对象,它会自动处理表单中的所有数据。
//language:js
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
let response = JSON.parse(this.responseText);
if (response.code == 0) {
alert('留言成功');
} else {
alert(response.msg);
}
}
xhttp.open("POST", "post-message.php", true);
var guestBookForm = document.getElementById("guestBookForm");
var formData = new FormData(guestBookForm);
xhttp.send(formData);
在这个例子中,我们发送一个 POST 请求到 post-message.php
,并通过 FormData
对象封装了表单中的数据。当 PHP 处理完请求后,返回一个 JSON 格式的响应,JavaScript 会根据返回的 code
来判断留言是否成功。
3. PHP 处理代码
以下是对应的 PHP 处理代码:
//language:php
<?php
include 'db.php';
$guestName = $_POST['guestName'];
$message = $_POST['message'];
if (empty($guestName)) {
echo json_encode(['code' => -1, 'msg' => '昵称不能为空']);
exit();
}
if (empty($message)) {
echo json_encode(['code' => -1, 'msg' => '留言内容不能为空']);
exit();
}
// 进一步的处理,如存入数据库等
?>
在 PHP 端,我们检查了用户提交的 guestName
和 message
是否为空。如果为空,则返回相应的错误信息。
4. 自定义 FormData
如果需要手动构建 FormData
,例如在动态生成数据时,可以这样做:
//language:js
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
let response = JSON.parse(this.responseText);
}
xhttp.open("POST", "pay.php", true);
var formData = new FormData();
formData.append("id", id);
formData.append("unitPrice", unitPrice);
formData.append("count", P[i]);
xhttp.send(formData);
通过这种方式,你可以灵活地向服务器发送任何自定义的数据。