一个简单的Ajax 配合 perl/cgi 示例

1. 工作流程

  1. 用户操作(如点击按钮)触发前端的 JavaScript 脚本。
  2. JavaScript 使用 AJAX 向服务器发送 HTTP 请求。
  3. Perl/CGI 脚本 在服务器端接收请求,处理数据(如查询数据库)并生成响应。
  4. AJAX 接收服务器返回的数据,更新网页内容而无需刷新整个页面

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. 示例结果

  1. 打开网页,点击 "Fetch Data" 按钮。
  2. 浏览器通过 AJAX 向 /cgi-bin/example.cgi 发送请求。
  3. Perl/CGI 脚本处理请求,并返回响应文本。
  4. 浏览器显示响应结果,例如:Server received query: test。