
在现代web开发中,从外部api获取数据是常见的任务。当api返回的数据格式为csv时,我们需要特定的工具来解析它,并确保数据能够正确地映射到我们定义的变量中。本教程将以一个具体的案例为例,详细介绍如何使用javascript和papaparse库从csv api获取学校信息,解析数据,并解决变量填充不正确的问题。
首先,我们需要一个基本的HTML页面来承载用户输入和触发数据获取的按钮,并引入PapaParse库来处理CSV数据。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>获取学校信息</title>
<!-- 引入 PapaParse 库,用于解析 CSV 数据 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.3.0/papaparse.min.js"></script>
</head>
<body>
<label for="schoolName">输入学校名称:</label>
<input type="text" id="schoolName" value="Duke University" />
<button onclick="getSchoolInformation()">获取信息</button>
<script>
// JavaScript 代码将放在这里
</script>
</body>
</html>在上述HTML中,我们创建了一个文本输入框 (schoolName) 用于接收用户输入的学校名称,一个按钮 (Get Information) 来触发数据获取函数,并引入了PapaParse库。
getSchoolInformation 函数是整个流程的入口点。它负责从用户界面获取学校名称,并向指定的CSV API发起fetch请求。
// Function to retrieve school information
function getSchoolInformation() {
let schoolName = document.getElementById("schoolName").value;
console.log("尝试获取的学校名称:", schoolName); // 调试输出,检查输入值
// 使用 fetch API 从 CSV 文件获取数据
fetch('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-03-10/tuition_cost.csv')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.text(); // 将响应体解析为纯文本
})
.then(csvData => {
// 成功获取 CSV 文本后,调用 findSchoolInformation 进行解析和筛选
let schoolInfo = findSchoolInformation(schoolName, csvData);
displaySchoolInformation(schoolInfo); // 显示结果
})
.catch(error => {
console.error('获取或解析数据时发生错误:', error); // 错误处理
});
}要点:
立即学习“Java免费学习笔记(深入)”;
findSchoolInformation 函数是核心部分,它接收原始CSV数据和用户输入的学校名称,然后使用PapaParse解析CSV,并根据学校名称筛选出相关信息。
解决变量填充问题的关键在于:确保在访问CSV数据时使用的列名与CSV文件头中的实际列名完全一致。
// Function to find school information based on school name
function findSchoolInformation(schoolName, csvData) {
// 使用 PapaParse 解析 CSV 数据
let parsedData = Papa.parse(csvData, {
header: true, // 将第一行作为列头,生成对象数组
skipEmptyLines: true // 跳过空行
}).data;
let schoolInfo = []; // 用于存储找到的学校信息
// 调试输出:检查解析后的数据结构和列名
if (parsedData.length > 0) {
console.log('解析后的第一行数据示例:', parsedData[0]);
// 开发者应根据此输出确认正确的列名
}
parsedData.forEach(function(row) {
// !!! 关键修正点:使用 CSV 文件中实际的列名 !!!
// 原始 CSV 文件的列名是 "name", "degree_length", "in_state_tuition"
let collegeName = row.name; // 使用点符号访问,更简洁
let degreeLength = row.degree_length;
let tuitionCost = row.in_state_tuition;
// 筛选条件:学校名称存在且与用户输入匹配(不区分大小写)
if (collegeName && collegeName.toLowerCase() === schoolName.toLowerCase()) {
// 对获取到的数据进行类型转换
// 注意:这里将 collegeName 转换为小写是为了存储,如果需要原始大小写,则不应转换
// collegeName = collegeName.toLowerCase();
degreeLength = parseInt(degreeLength);
tuitionCost = parseFloat(tuitionCost);
// 确保转换后的数值有效
if (!isNaN(degreeLength) && !isNaN(tuitionCost)) {
schoolInfo.push({
collegeName: collegeName, // 存储原始或转换后的名称,取决于需求
degreeLength: degreeLength,
tuitionCost: tuitionCost
});
}
}
});
console.log('筛选到的学校信息:', schoolInfo); // 调试输出,检查筛选结果
return schoolInfo;
}要点解析:
displaySchoolInformation 函数负责将找到的学校信息输出到控制台。
// Function to display school information in the console
function displaySchoolInformation(schoolInfo) {
if (schoolInfo.length === 0) {
console.log("未找到匹配的学校信息。");
return;
}
for (let i = 0; i < schoolInfo.length; i++) {
let collegeName = schoolInfo[i].collegeName;
let degreeLength = schoolInfo[i].degreeLength;
let tuitionCost = schoolInfo[i].tuitionCost;
console.log("学校名称: " + collegeName);
console.log("学制长度: " + degreeLength);
console.log("学费 (州内): $" + tuitionCost.toFixed(2)); // 格式化为两位小数
console.log("------------------------------");
}
}要点:
立即学习“Java免费学习笔记(深入)”;
将上述所有JavaScript代码整合到HTML文件的<script>标签中,即可运行。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>获取学校信息</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.3.0/papaparse.min.js"></script>
</head>
<body>
<label for="schoolName">输入学校名称:</label>
<input type="text" id="schoolName" value="Duke University" />
<button onclick="getSchoolInformation()">获取信息</button>
<script>
// Function to retrieve school information
function getSchoolInformation() {
let schoolName = document.getElementById("schoolName").value;
console.log("尝试获取的学校名称:", schoolName);
fetch('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-03-10/tuition_cost.csv')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.text();
})
.then(csvData => {
let schoolInfo = findSchoolInformation(schoolName, csvData);
displaySchoolInformation(schoolInfo);
})
.catch(error => {
console.error('获取或解析数据时发生错误:', error);
});
}
// Function to find school information based on school name
function findSchoolInformation(schoolName, csvData) {
let parsedData = Papa.parse(csvData, {
header: true,
skipEmptyLines: true
}).data;
let schoolInfo = [];
if (parsedData.length > 0) {
console.log('解析后的第一行数据示例:', parsedData[0]);
}
parsedData.forEach(function(row) {
let collegeName = row.name;
let degreeLength = row.degree_length;
let tuitionCost = row.in_state_tuition;
if (collegeName && collegeName.toLowerCase() === schoolName.toLowerCase()) {
degreeLength = parseInt(degreeLength);
tuitionCost = parseFloat(tuitionCost);
if (!isNaN(degreeLength) && !isNaN(tuitionCost)) {
schoolInfo.push({
collegeName: collegeName,
degreeLength: degreeLength,
tuitionCost: tuitionCost
});
}
}
});
console.log('筛选到的学校信息:', schoolInfo);
return schoolInfo;
}
// Function to display school information in the console
function displaySchoolInformation(schoolInfo) {
if (schoolInfo.length === 0) {
console.log("未找到匹配的学校信息。");
return;
}
for (let i = 0; i < schoolInfo.length; i++) {
let collegeName = schoolInfo[i].collegeName;
let degreeLength = schoolInfo[i].degreeLength;
let tuitionCost = schoolInfo[i].tuitionCost;
console.log("学校名称: " + collegeName);
console.log("学制长度: " + degreeLength);
console.log("学费 (州内): $" + tuitionCost.toFixed(2));
console.log("------------------------------");
}
}
</script>
</body>
</html>通过遵循本教程的步骤和建议,您将能够更有效地从CSV API获取、解析和处理数据,避免常见的变量填充错误,并构建出更加稳定和可靠的Web应用程序。
以上就是JavaScript教程:正确从CSV API获取、解析并填充变量的实践指南的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号