php
<?php // 定义名言名句数组 $quotes = array( "名言1", "名言2", "名言3", // 添加更多名言... ); // 从数组中随机选择一条名言 $randomQuote = $quotes[array_rand($quotes)]; // 设置响应头为 JSON 格式 header('Content-Type: application/json'); // 构建 JSON 响应数据 $response = array( 'quote' => $randomQuote ); // 将响应数据输出,确保不对中文字符进行 Unicode 编码 echo json_encode($response, JSON_UNESCAPED_UNICODE); ?>
<!DOCTYPE html> <html> <head> <title>随机名言名句</title> <script> function getRandomQuote() { // 创建一个新的 XMLHttpRequest 对象 var xhr = new XMLHttpRequest(); // 指定请求的方法和 URL xhr.open('GET', 'random_quote.php', true); // 处理响应结果 xhr.onreadystatechange = function() { if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) { // 解析 JSON 响应 var response = JSON.parse(xhr.responseText); // 调用显示名言的函数 displayQuote(response.quote); } }; // 发送请求 xhr.send(); } function displayQuote(quote) { // 将名言显示在指定的元素中 document.getElementById('quote').textContent = quote; } </script> </head> <body> <h1>随机名言名句</h1> <button onclick="getRandomQuote()">获取随机名言名句</button> <p id="quote"></p> </body> </html>
Comments NOTHING