我想你一個支持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>
謝謝你的回答佐爾坦。事情是我的網站訪客將城市名稱鍵入文本框,而不是下拉菜單。你能幫我修改代碼嗎?欣賞它 –
你有夥伴,我希望這會有所幫助。 –
謝謝佐爾坦,它工作正常。新年快樂給你和你的家人..... :) –