1. 工作流程
2. 实现步骤
前端:使用 AJAX 发出请求
使用 JavaScript(通过 XMLHttpRequest 或 Fetch API)发出 AJAX 请求。例如:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AJAX with Perl/CGI</title>
<script>
function fetchData() {
// 创建 XMLHttpRequest 对象
let xhr = new XMLHttpRequest();
// 指定请求的 CGI 脚本 URL 和参数
xhr.open("GET", "/cgi-bin/example.cgi?query=test", true);
// 定义回调函数
xhr.onload = function () {
if (xhr.status === 200) {
// 接收服务器响应并更新网页
document.getElementById("result").innerHTML = xhr.responseText;
} else {
console.error("Error:", xhr.status);
}
};
// 发送请求
xhr.send();
}
</script>
</head>
<body>
<h1>AJAX with Perl/CGI Example</h1>
<button onclick="fetchData()">Fetch Data</button>
<div id="result">Response will appear here.</div>
</body>
</html>
服务器端:Perl/CGI 脚本处理请求
Perl 脚本处理客户端请求并返回响应:
#!/usr/bin/perl
use strict;
use warnings;
use CGI;
# 创建 CGI 对象
my $cgi = CGI->new;
# 设置响应头
print $cgi->header('text/plain');
# 获取客户端发送的参数
my $query = $cgi->param('query') || 'default';
# 模拟一些数据处理
my $response = "Server received query: $query";
# 返回响应数据
print $response;
3. 示例结果