家明故事

AJAX请求PHP返回JSON数据示例

家明 0 0

AJAX请求PHP返回JSON数据示例

下面是一个完整的示例,展示如何使用AJAX请求PHP页面并接收JSON格式的响应数据。

思路分析

  1. 创建前端页面,使用JavaScript发起AJAX请求

  2. 编写PHP后端脚本,正确处理数据并返回JSON格式

  3. 前端接收并解析JSON数据,动态更新页面内容

完整代码实现

html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AJAX请求PHP返回JSON数据</title>
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        body {
            background-color: #f5f7fa;
            color: #333;
            line-height: 1.6;
            padding: 20px;
        }
        
        .container {
            max-width: 1000px;
            margin: 0 auto;
            padding: 20px;
        }
        
        header {
            text-align: center;
            margin-bottom: 30px;
            padding: 20px;
            background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
            color: white;
            border-radius: 10px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
        }
        
        h1 {
            font-size: 2.5rem;
            margin-bottom: 10px;
        }
        
        .description {
            font-size: 1.1rem;
            opacity: 0.9;
        }
        
        .content {
            display: flex;
            gap: 20px;
            flex-wrap: wrap;
        }
        
        .request-panel, .response-panel {
            flex: 1;
            min-width: 300px;
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.08);
        }
        
        h2 {
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #eee;
            color: #2575fc;
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: 600;
            color: #555;
        }
        
        input, select {
            width: 100%;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 16px;
            transition: border 0.3s;
        }
        
        input:focus, select:focus {
            outline: none;
            border-color: #2575fc;
            box-shadow: 0 0 0 2px rgba(37, 117, 252, 0.2);
        }
        
        button {
            background: #2575fc;
            color: white;
            border: none;
            padding: 12px 20px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            font-weight: 600;
            transition: background 0.3s;
            width: 100%;
        }
        
        button:hover {
            background: #1c64e0;
        }
        
        .response-content {
            background: #f8f9fa;
            border-radius: 5px;
            padding: 15px;
            margin-top: 20px;
            min-height: 200px;
            max-height: 400px;
            overflow-y: auto;
            border: 1px solid #eee;
        }
        
        pre {
            white-space: pre-wrap;
            word-break: break-all;
            font-family: 'Consolas', monospace;
        }
        
        .user-card {
            background: white;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 15px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
            border-left: 4px solid #2575fc;
        }
        
        .user-card h3 {
            color: #2575fc;
            margin-bottom: 10px;
        }
        
        .user-card p {
            margin-bottom: 5px;
        }
        
        .status {
            padding: 8px 12px;
            border-radius: 20px;
            font-size: 14px;
            font-weight: 600;
            display: inline-block;
            margin-top: 10px;
        }
        
        .status.success {
            background: #e6f7ee;
            color: #0c9d58;
        }
        
        .status.error {
            background: #feeaea;
            color: #f44336;
        }
        
        .loader {
            display: none;
            text-align: center;
            margin: 20px 0;
        }
        
        .loader div {
            width: 12px;
            height: 12px;
            background: #2575fc;
            border-radius: 50%;
            display: inline-block;
            margin: 0 3px;
            animation: loader 1.2s infinite ease-in-out both;
        }
        
        .loader div:nth-child(1) { animation-delay: -0.32s; }
        .loader div:nth-child(2) { animation-delay: -0.16s; }
        
        @keyframes loader {
            0%, 80%, 100% { transform: scale(0); }
            40% { transform: scale(1); }
        }
        
        @media (max-width: 768px) {
            .content {
                flex-direction: column;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>AJAX请求PHP返回JSON数据</h1>
            <p class="description">演示如何使用AJAX从PHP获取JSON格式的响应数据</p>
        </header>
        
        <div class="content">
            <div class="request-panel">
                <h2>发送请求</h2>
                <div class="form-group">
                    <label for="userCount">用户数量</label>
                    <select id="userCount">
                        <option value="1">1个用户</option>
                        <option value="3" selected>3个用户</option>
                        <option value="5">5个用户</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label for="dataType">响应格式</label>
                    <select id="dataType">
                        <option value="users" selected>用户数据</option>
                        <option value="products">产品数据</option>
                    </select>
                </div>
                
                <button id="sendRequest">发送AJAX请求</button>
                
                <div class="loader" id="loader">
                    <div></div>
                    <div></div>
                    <div></div>
                </div>
            </div>
            
            <div class="response-panel">
                <h2>响应结果</h2>
                <div id="responseContent" class="response-content">
                    <p id="placeholder">点击"发送AJAX请求"按钮获取数据...</p>
                    <div id="result"></div>
                </div>
            </div>
        </div>
    </div>

    <script>
        document.getElementById('sendRequest').addEventListener('click', function() {
            // 显示加载动画
            document.getElementById('loader').style.display = 'block';
            document.getElementById('placeholder').style.display = 'none';
            document.getElementById('result')[xss_clean] = '';
            
            // 获取用户选择的参数
            const userCount = document.getElementById('userCount').value;
            const dataType = document.getElementById('dataType').value;
            
            // 创建AJAX请求
            const xhr = new XMLHttpRequest();
            xhr.open('POST', 'simulate-ajax-handler.php', true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4) {
                    // 隐藏加载动画
                    document.getElementById('loader').style.display = 'none';
                    
                    if (xhr.status === 200) {
                        try {
                            // 解析返回的JSON数据
                            const response = JSON.parse(xhr.responseText);
                            
                            // 显示成功状态
                            displayStatus('success', '请求成功!');
                            
                            // 处理并显示数据
                            displayResponse(response);
                        } catch (e) {
                            displayStatus('error', '解析JSON数据时出错: ' + e.message);
                        }
                    } else {
                        displayStatus('error', '请求失败,状态码: ' + xhr.status);
                    }
                }
            };
            
            // 发送请求
            xhr.send('count=' + userCount + '&type=' + dataType);
        });
        
        function displayStatus(type, message) {
            const statusElement = document.createElement('div');
            statusElement.className = 'status ' + type;
            statusElement.textContent = message;
            document.getElementById('result').appendChild(statusElement);
        }
        
        function displayResponse(data) {
            const resultDiv = document.getElementById('result');
            
            // 显示原始JSON数据
            const pre = document.createElement('pre');
            pre.textContent = JSON.stringify(data, null, 2);
            resultDiv.appendChild(pre);
            
            // 如果返回的是用户数据,则进行格式化显示
            if (data.users) {
                data.users.forEach(user => {
                    const userCard = document.createElement('div');
                    userCard.className = 'user-card';
                    userCard[xss_clean] = `
                        <h3>${user.name}</h3>
                        <p><strong>邮箱:</strong> ${user.email}</p>
                        <p><strong>电话:</strong> ${user.phone}</p>
                        <p><strong>注册时间:</strong> ${user.registration_date}</p>
                    `;
                    resultDiv.appendChild(userCard);
                });
            }
            
            // 如果返回的是产品数据,则进行格式化显示
            if (data.products) {
                data.products.forEach(product => {
                    const productCard = document.createElement('div');
                    productCard.className = 'user-card';
                    productCard[xss_clean] = `
                        <h3>${product.name}</h3>
                        <p><strong>价格:</strong> $${product.price}</p>
                        <p><strong>库存:</strong> ${product.stock} 件</p>
                        <p><strong>分类:</strong> ${product.category}</p>
                    `;
                    resultDiv.appendChild(productCard);
                });
            }
        }
    </script>
</body>
</html>

PHP代码示例 (simulate-ajax-handler.php)

php
<?php
// 设置响应头为JSON格式
header('Content-Type: application/json');

// 允许跨域请求(根据需要设置)
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header('Access-Control-Allow-Headers: Content-Type');

// 获取请求参数
$count = isset($_POST['count']) ? intval($_POST['count']) : 3;
$type = isset($_POST['type']) ? $_POST['type'] : 'users';

// 模拟用户数据
$users = [];
for ($i = 1; $i <= $count; $i++) {
    $users[] = [
        'id' => $i,
        'name' => '用户 ' . $i,
        'email' => 'user' . $i . '@example.com',
        'phone' => '1380013800' . $i,
        'registration_date' => date('Y-m-d', strtotime('-'.rand(0, 365).' days'))
    ];
}

// 模拟产品数据
$products = [];
for ($i = 1; $i <= $count; $i++) {
    $products[] = [
        'id' => $i,
        'name' => '产品 ' . $i,
        'price' => number_format(rand(100, 2000) / 10, 2),
        'stock' => rand(0, 100),
        'category' => ['电子产品', '服装', '食品', '图书'][rand(0, 3)]
    ];
}

// 根据请求类型返回相应的数据
if ($type === 'users') {
    $response = [
        'status' => 'success',
        'message' => '成功获取用户数据',
        'users' => $users,
        'count' => $count
    ];
} else {
    $response = [
        'status' => 'success',
        'message' => '成功获取产品数据',
        'products' => $products,
        'count' => $count
    ];
}

// 输出JSON数据
echo json_encode($response, JSON_UNESCAPED_UNICODE);

// 结束脚本执行
exit;
?>

关键点说明

  1. PHP返回JSON数据的关键步骤

    • 设置响应头:header('Content-Type: application/json');

    • 构建数据数组

    • 使用json_encode()将数组转换为JSON字符串

    • 使用echo输出JSON字符串

  2. 前端处理

    • 使用XMLHttpRequest或Fetch API发送请求

    • 设置正确的请求头(如果需要)

    • 解析返回的JSON数据:JSON.parse(responseText)

    • 动态更新页面内容

  3. 注意事项

    • 确保PHP脚本没有输出任何其他内容(包括空格),否则会影响JSON解析

    • 处理可能出现的错误(网络错误、解析错误等)

    • 根据需求设置适当的CORS头

这个示例可以直接保存为HTML文件并在支持PHP的服务器环境中运行。

标签:AJAX  PHP  

打赏

发表评论