我假设您在启用 PHP 的 Web 服务器上运行您的网站,不是吗?在这种情况下,这是一个适合您的解决方案,它使用 PHP 逐行读取 csv 文件并创建一个 html 下拉列表供用户按名称选择城市。
此外,如果您的服务器上没有运行 PHP,则可以使用 JavaScript 执行相同的操作,如果您需要它而不是 PHP,请告诉我。
这可能是最简单的解决方案,如果您想使用文本输入而不是下拉列表中的城市列表,您可以通过实现 javascript 自动完成功能来获得进一步的解决方案。
<form action="vendor.com" method="get" target="_blank">
Please select city:
<?php
// Set filename to read from
$csvFile = 'dummy.csv';
// Open file handle
$fp = fopen($csvFile, "r");
// In case the file don't exist, exit
if (!is_resource($fp)){
die("Cannot open $csvFile");
}
?>
<select name="city">
<?php //Let's read the csvfile line by line: ?>
<?php while($line = fgetcsv($fp)): ?>
<?php // Assuming that the csvfile's structure is the following: city_id,city_name, we create the dropdown options: ?>
<option value="<?php echo $line[0];?>"><?php echo $line[1]?></option>
<?php endwhile; ?>
</select>
<input type="submit" value="Submit">
</form>
现在这是 JavaScript 解决方案(代码使用 JQUERY 框架,因此您必须将其包含在您的 html 标记中:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
您还需要一个隐藏的表单输入来包含匹配的城市 ID,因此这里是您的表单的扩展 html 标记:
<form action="vendor.com" method="get" target="_blank" id="myForm">
Please enter city name:-
<input type="hidden" id="cityId" name="cityId">
<input type="text" id="cityName" name="cityName">
<input type="submit" value="Submit">
</form>
和你的 JavaScript 来完成这项工作:
<script>
$(function(){
//Ajax call to get csv file contents
$.ajax({
type: "GET",
url: "dummy.csv",
dataType: "text",
success: function(data) {process_csv(data);}
});
//Event handler for form submission
$('#myForm').submit(function(){
//Let's get the value of the text input (city name)
var city_name = $('#cityName').val().toLowerCase();
//If the city name exists in our map, let's set the matched city id to the hidden input field called cityId
if (city_ids[city_name] > 0)
{
$('#cityId').val(city_ids[city_name]);
return true;
}
//Otherwise we can't find the city id in our database, so we can't post the form either...
alert('No such city name in database!');
return false;
});
});
//global variable to contain map of city names and id's
var city_ids = {};
//Function to parse csv file and set city map
function process_csv(text) {
var lines = text.split(/\r\n|\n/);
for (var i=0; i<lines.length; i++) {
var data = lines[i].split(',');
city_ids[data[1].toLowerCase()] = data[0];
}
}
</script>