我已经改变了我的代码,只使用一个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”,因为这是我所能达到的最大故事数量。
1条答案
按热度按时间2vuwiymt1#
你可以修改argentina.php如下:
这将返回请求的故事,但如果URL参数 story 丢失,则返回随机故事。
代码更新:如果参数缺失,则返回随机故事或0。感谢CBroe!