When troubleshooting issues with fetching Wikipedia data, especially when using the Wikipedia API with JavaScript, there are several key areas to consider:
-
Cross-Origin Resource Sharing (CORS): The most common issue that arises when using the Wikipedia API directly from a web page is CORS restrictions. The origin=* parameter in the API URL is meant to allow requests from any origin, but CORS still needs to be appropriately handled by your browser and the configuration.
-
API URL: Ensure the URL you are using is correctly formatted. The Wikipedia API endpoint can sometimes be misunderstood, especially regarding dynamic data requests.
-
Fetch Errors: Check for fetch errors and ensure you are catching errors properly in the JavaScript console.
Here is a revised example to ensure better handling:
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>iOS Стиль Википедии</title>
<link href="https://fonts.googleapis.com/css2?family=Raleway:wght@400;600&family=Inter:wght@400;500&display=swap" rel="stylesheet">
<!-- For Charts -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
body {
font-family: 'Inter', sans-serif;
margin: 0;
padding: 0;
background-color: #f0f0f0;
}
header {
background-color: white;
padding: 20px;
text-align: center;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
.header-title {
font-size: 24px;
color: #007aff;
font-family: 'Raleway', sans-serif;
}
.container {
display: flex;
flex-direction: column;
max-width: 1200px;
margin: 20px auto;
padding: 10px;
}
.content {
flex: 3;
background-color: white;
padding: 20px;
border-radius: 12px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
margin-bottom: 20px;
}
h1 {
font-size: 28px;
color: #007aff;
font-family: 'Raleway', sans-serif;
}
h2 {
font-size: 22px;
color: #007aff;
margin-top: 30px;
}
p {
font-size: 16px;
color: #333;
line-height: 1.6;
}
.search-section {
margin-bottom: 20px;
}
.search-section input {
padding: 12px;
width: 80%;
font-size: 16px;
margin-right: 10px;
border-radius: 12px;
border: 1px solid #007aff;
}
.search-section button {
padding: 12px;
font-size: 16px;
background-color: #007aff;
color: white;
border: none;
border-radius: 12px;
cursor: pointer;
}
a {
color: #007aff;
font-weight: bold;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
.section {
margin-bottom: 20px;
padding: 15px;
border-radius: 12px;
background-color: #f9f9f9;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}
table {
width: 100%;
border-collapse: collapse;
margin-bottom: 20px;
}
table, th, td {
border: 1px solid #ddd;
}
th, td {
padding: 12px;
text-align: left;
}
th {
background-color: #f4f4f4;
font-family: 'Raleway', sans-serif;
}
.chart-container {
margin-top: 40px;
background-color: white;
padding: 20px;
border-radius: 12px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
footer {
background-color: white;
text-align: center;
padding: 20px;
font-size: 14px;
color: #808080;
box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1);
margin-top: 20px;
}
</style>
</head>
<body>
<header>
<div class="header-title">РУВИКИ</div>
</header>
<div class="container">
<div class="content">
<h1>Поиск информации</h1>
<div class="search-section">
<input type="text" id="searchTerm" placeholder="Введите запрос для поиска">
<button onclick="searchWiki()">Поиск</button>
</div>
<div id="result" class="article-info"></div>
</div>
</div>
<div class="chart-container" id="chartContainer" style="display: none;">
<canvas id="chart"></canvas>
</div>
<footer>
© 2024 Рувики. Все права защищены.
</footer>
<script>
function searchWiki() {
const searchTerm = document.getElementById('searchTerm').value;
const apiUrl = `https://ru.wikipedia.org/w/api.php?action=query&list=search&srsearch=${encodeURIComponent(searchTerm)}&utf8=&format=json&origin=*`;
fetch(apiUrl)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
const resultDiv = document.getElementById('result');
resultDiv.innerHTML = '';
if (data.error) {
resultDiv.innerHTML = '<p>Ошибка в запросе API: ' + data.error.info + '</p>';
} else if (data.query.search.length === 0) {
resultDiv.innerHTML = '<p>Ничего не найдено.</p>';
} else {
const pageTitle = data.query.search[0].title;
getWikiPage(pageTitle);
}
})
.catch(error => {
console.error('Ошибка при запросе:', error);
document.getElementById('result').innerHTML = '<p>Ошибка при запросе: ' + error.message + '</p>';
});
}
function getWikiPage(pageTitle) {
const pageUrl = `https://ru.wikipedia.org/w/api.php?action=parse&page=${encodeURIComponent(pageTitle)}&format=json&origin=*`;
fetch(pageUrl)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
const resultDiv = document.getElementById('result');
resultDiv.innerHTML = '';
if (data.error) {
resultDiv.innerHTML = '<p>Ошибка при получении данных страницы: ' + data.error.info + '</p>';
} else if (data.parse) {
const pageContent = data.parse.text['*'];
const container = document.createElement('div');
container.innerHTML = pageContent;
const sections = container.querySelectorAll('h2, h3, p, table');
sections.forEach(section => {
const sectionWrapper = document.createElement('div');
sectionWrapper.className = 'section';
sectionWrapper.appendChild(section.cloneNode(true));
resultDiv.appendChild(sectionWrapper);
});
// Update links to styled
const links = resultDiv.querySelectorAll('a');
links.forEach(link => {
link.style.color = '#007aff';
link.style.fontWeight = 'bold';
});
// Optionally display a chart example
displayChart();
}
})
.catch(error => {
console.error('Ошибка при запросе страницы:', error);
document.getElementById('result').innerHTML = '<p>Ошибка при запросе страницы: ' + error.message + '</p>';
});
}
function displayChart() {
const ctx = document.getElementById('chart').getContext('2d');
const chartContainer = document.getElementById('chartContainer');
chartContainer.style.display = 'block';
new Chart(ctx, {
type: 'bar',
data: {
labels: ['Январь', 'Февраль', 'Март', 'Апрель', 'Май'],
datasets: [{
label: 'Посещения',
data: [10, 20, 30, 40, 50],
backgroundColor: '#007aff'
}]
},
options: {
responsive: true,
scales: {
x: {
beginAtZero: true
},
y: {
beginAtZero: true
}
}
}
});
}
</script>
</body>
</html>
Fixes and Improvements:
- Encoding the Search Term: Using
encodeURIComponent() ensures that any characters in the search term that could pose problems (such as spaces or special characters) are appropriately encoded for a URL.
- Error Handling: Added checks and descriptive error messages for better diagnostics of what might be going wrong, both for network and API issues.
- Network Response Validation: Check the HTTP response to ensure it's ok before attempting to parse the body as JSON.
These modifications should improve the reliability of the Wikipedia search feature, ensuring it handles various input scenarios and potential network issues. If you're still encountering issues, consider running the application on a server rather than opening the HTML file directly in a browser, as some browsers enforce stricter CORS policies on local files.