php 随机故事按钮尝试生成故事1-1000

x4shl7ld  于 2023-10-15  发布在  PHP
关注(0)|答案(1)|浏览(95)

我已经改变了我的代码,只使用一个JavaScript文件和一个PHP文件

HTML

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Stories - USA</title>
    <link rel="stylesheet" href="../CSS/country.css">
</head>
<body data-country="usa">
  <header>
      <h1>Stories</h1>
      <h3>United States of America</h3>
  </header>
    <main>
      <div id="content-wrapper">
        <div id="get-container">
          <input type="text" id="story-number" placeholder="Enter story number">
          <button id="get" type="button">Get Story</button>
          <button id="getRandom" type="button">Random Story</button>
        </div>
        <div id="story-container">
          <!-- Story content will be displayed here -->
          <div id="generated-text"></div>
          <button id="back" type="button">Back</button>
        </div>
    </main>
    <script src="Scripts/country.js"></script>
</body>
</html>

country.js

document.addEventListener('DOMContentLoaded', function () {
    var storyContainer = document.getElementById('story-container');
    var storyNumberInput = document.getElementById('story-number');
    var getButton = document.getElementById('get');
    var getRandomButton = document.getElementById('getRandom');
    var clearButton = document.getElementById('back');

    // Determine the country from the URL
    var country = getCountryFromURL();

    function getCountryFromURL() {
        var url = window.location.href;
        if (url.includes('united-states-of-america.html')) {
            return 'usa';
        } else if (url.includes('sweden.html')) {
            return 'sweden';
        } else {
            return 'argentina';
        }
        // Add more countries here
    }

    // Define an object to map countries to their text files and actual total stories
    var countryData = {
        'argentina': {
            file: 'argentina.txt',
            actualTotalStories: 3 // Update this based on your actual stories
        },
        'usa': {
            file: 'usa.txt',
            actualTotalStories: 1000 // Update this based on your actual stories
        },
        'sweden': {
            file: 'sweden.txt',
            actualTotalStories: 5 // Update this based on your actual stories
        },
        // Add more countries as needed
    };

    function clearStoryContainer() {
        if (storyContainer) {
            storyContainer.style.display = 'none';
            var generatedTextElement = document.getElementById('generated-text');
            if (generatedTextElement) {
                generatedTextElement.innerHTML = '';
            }
            storyNumberInput.value = '';
            clearButton.style.display = 'none';
            storyContainer.scrollTop = 0;
        }
    }

    function fetchStory(country, storyNumber) {
        clearStoryContainer();

        if (storyNumber === '0') {
            // Generate a random story number between 1 and totalStories for the selected country
            var randomStoryNumber = Math.floor(Math.random() * countryData[country].actualTotalStories) + 1;
            storyNumber = randomStoryNumber;
        }

        var xhr = new XMLHttpRequest();
        xhr.open('GET', 'PHP/router.php?country=' + encodeURIComponent(country) + '&story=' + encodeURIComponent(storyNumber), true);

        xhr.onload = function () {
            if (xhr.status === 200) {
                var generatedText = xhr.responseText;
                if (storyContainer) {
                    storyContainer.style.display = 'block';
                    var generatedTextElement = document.getElementById('generated-text');
                    if (generatedTextElement) {
                        generatedTextElement.innerHTML = parseAndStyleTitles(generatedText);
                    }
                    clearButton.style.display = 'inline-block';
                    storyContainer.scrollTop = 0;
                }
            } else {
                console.log('Error fetching story. Status code: ' + xhr.status);
                clearStoryContainer();
                if (xhr.status === 404) {
                    displayErrorMessage('The story file does not exist.');
                } else {
                    displayErrorMessage('Error fetching story.');
                }
            }
        };
        xhr.onerror = function () {
            console.log('Network error while fetching story.');
            clearStoryContainer();
            displayErrorMessage('Network error while fetching story.');
        };
        xhr.send();
    }

    function displayErrorMessage(errorMessage) {
        if (storyContainer) {
            storyContainer.style.display = 'block';
        }
        var generatedTextElement = document.getElementById('generated-text');
        if (generatedTextElement) {
            generatedTextElement.innerHTML = errorMessage;
        }
    }

    function parseAndStyleTitles(text) {
        return text.replace(/\[\[(.*?)\]\]/g, function (match, title) {
            return '<span>' + title + '</span>';
        });
    }

    if (getButton) {
        getButton.addEventListener('click', function () {
            var storyNumber = storyNumberInput.value;
            fetchStory(country, storyNumber);
        });
    }

    if (getRandomButton) {
        getRandomButton.addEventListener('click', function () {
            fetchStory(country, '0');
        });
    }

    if (clearButton) {
        clearButton.addEventListener('click', function () {
            clearStoryContainer();
        });
    }
});

router.php

<?php
if (isset($_GET['country'])) {
    $country = $_GET['country'];
    $storyNumber = $_GET['story'];

    // Define an array of valid countries and their corresponding text files
    $validCountries = array(
        'argentina' => 'argentina.txt',
        'usa' => 'usa.txt',
        'sweden' => 'sweden.txt',
        // Add more countries and their text files as needed
    );

    if (isset($validCountries[$country])) {
        $file = '../../Stories/' . $validCountries[$country];
    } else {
        // Return an error if the requested country does not exist
        echo 'The requested country does not exist.';
        exit;
    }

    if (file_exists($file)) {
        // Read the content of the text file
        $fileContent = file_get_contents($file);

        // Split the content into stories based on the delimiter
        $stories = preg_split('/<!-- Unique delimiter separating stories -->/', $fileContent);

        // Determine the actual number of stories
        $actualTotalStories = count($stories);

        if ($storyNumber === '0') {
            // Generate a random story number within the range of actual stories
            $storyNumber = rand(1, $actualTotalStories);
        } else {
            $storyNumber = intval($storyNumber);
        }

        if ($storyNumber >= 1 && $storyNumber <= $actualTotalStories) {
            // Check if the requested story exists
            $requestedStory = trim($stories[$storyNumber - 1]);

            // Replace "\r\n\r\n" with "<br><br>" for paragraphs
            $formattedStory = str_replace("\r\n\r\n", "<br><br>", $requestedStory);

            // Replace remaining "\r\n" with "<br>" for line breaks within paragraphs
            $formattedStory = str_replace("\r\n", "<br>", $formattedStory);

            echo $formattedStory;
        } else {
            // Return an error if the requested story does not exist
            echo 'The requested story does not exist.';
        }
    } else {
        // Return an error if the story file does not exist
        echo 'The story file does not exist.';
    }
} else {
    // Return an error for an invalid request
    echo 'Invalid request.';
}

?>

使用“获取故事”按钮工作得很好,但当我使用“随机故事”按钮时,它试图获取故事1-1000,即使我到目前为止在usa.txt中只有6个故事。
当我在文本文件中有6个故事时,我希望它获取1-6,直到我添加故事7,然后我希望它获取1-7。但我确实想保留“实际的TotalStories:1000”,因为这是我所能达到的最大故事数量。

2vuwiymt

2vuwiymt1#

你可以修改argentina.php如下:

<?php    
// Read the content of argentina.txt (relative to the location of this PHP file)
$storiesFile = file_get_contents('../../Stories/argentina.txt');

// Split the content into stories based on the unique delimiter (<!-- Unique delimiter separating stories -->)
$stories = preg_split('/<!-- Unique delimiter separating stories -->/', $storiesFile);

// Determine the actual number of stories
$actualTotalStories = count($stories);

// Read the requested story number from the URL parameter
$storyNumber = (isset($_GET['story']) && $_GET['story']!='0') ? $_GET['story'] : rand(1, $actualTotalStories);

if ($storyNumber >= 1 && $storyNumber <= $actualTotalStories) {
    // Check if the requested story exists
    $requestedStory = trim($stories[$storyNumber - 1]);
    $formattedStory = nl2br($requestedStory);
    echo $formattedStory;
} else {
    echo 'Error: Story not found.';
}

这将返回请求的故事,但如果URL参数 story 丢失,则返回随机故事。

代码更新:如果参数缺失,则返回随机故事0。感谢CBroe!

相关问题