AJAX方法(已测试)
PHP 处理程序
(find_in_file_ajax.php)
<?php
$search = $_POST['search'];
$text = file_get_contents('zipcodes.txt');
$lines = explode("\n", $text);
if(in_array($_POST['search'], $lines)){ //checks if ZIP is in array
echo "ZIP code found";
}else{
echo "ZIP code does not exist";
}
?>
HTML 表单
<!DOCTYPE html>
<html>
<head>
<style>
.update {
font-family:Georgia;
color:#0000FF;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".search_button").click(function() {
// getting the value that user typed
var searchString = $("#search_box").val();
// forming the queryString
var data = 'search='+ searchString;
// if searchString is not empty
if(searchString) {
// ajax call
$.ajax({
type: "POST",
url: "find_in_file_ajax.php",
data: data,
beforeSend: function(html) { // this happens before actual call
$("#results").html('');
$("#searchresults").show();
$(".word").html(searchString);
},
success: function(html){ // this happens after we get results
$("#results").show();
$("#results").append(html);
}
});
}
return false;
});
});
</script>
</head>
<body>
<div id="container">
<div>
<form method="post" action="">
<input type="text" name="search" id="search_box" class='search_box'/>
<input type="submit" value="Search" class="search_button" /><br />
</form>
</div>
<div>
<div id="searchresults">Search results: <span id="results" class="update"></span>
</div>
</div>
</div>
</body>
</html>
原始答案
经过测试
首先需要通过 访问该文件file_get_contents
,然后分解每个条目并提取有问题的邮政编码搜索。
假设 zipcodes.txt 文件格式如下:
43505
43517
43518
43526
43543
注意:如果查询 43505,就会找到。不像 4350 或 3505 不会被找到,所以它是一个唯一的查询。
考虑以下:
<?php
$search = $_POST['search'];
$text = file_get_contents('zipcodes.txt');
$lines = explode("\n", $text);
if(in_array($_POST['search'], $lines)){ //checks if ZIP is in array
echo "ZIP code found.";
}else{
echo "ZIP code does not exist";
}
?>