我想你一个支持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>
谢谢你的回答佐尔坦。事情是我的网站访客将城市名称键入文本框,而不是下拉菜单。你能帮我修改代码吗?欣赏它 –
你有伙伴,我希望这会有所帮助。 –
谢谢佐尔坦,它工作正常。新年快乐给你和你的家人..... :) –