我想要一个用户输入一个国家,然后它会输出它的人口。我的javascript是假设查找用户在点击按钮时输入的国家,然后浏览PHP文件并获取该国的人口。如何通过ajax检索数据?
我的HTML是:
<label>
Country:
<input name="country" type="text" id="country"></label>
<input type="button" value="Find population" id="findPop">
<p id="output"></p
和javascript:
var countryFound = function(data) {
var theCountry = $("#country").val();
var population = data["country"];
if (data["country"])
{
$("#output").html(theCountry + " population is " + population);
}
else {
$("#output").html(theCountry + " is not found");
}
};
$("#findPop").click(function(){
var theCountry = $("#country").val();
$("#output").html("Loading...");
$.getJSON("countrylookup.php", "country="+theCountry , countryFound);
});
我的PHP代码:
if (isset($_GET['country'])) { // get the parameters country
$column = 'country';
$value = $_GET['country'];
else {
print -1; // an error code
return;
}
$data = array('country'=>'Peru', 'capital'=>'Lima', 'area'=>'1285220', 'population'=>'29907003', 'continent'=>'South America'),
array('country'=>'Philippines', 'capital'=>'Manila', 'area'=>'300000', 'population'=>'99900177', 'continent'=>'Asia');
function findData ($whichColumn, $data, $searchValue)
{
$result = array();
foreach ($data as $row) {
if ($row[$whichColumn] == $searchValue)
$result[] = $row;
}
return $result;
}
print json_encode (findData($column, $data, $value));
但由于某些原因,当我输入秘鲁的国家,它说Peru is not found
。我没有检索到正确的数据从PHP或什么?我很确定我的php代码是正确的。
我能忍受吗?似乎没有人提出明显的?你的'$ data'变量有两个由逗号分隔的数组,这只是一个语法错误,根本不能工作? – adeneo 2013-03-10 21:05:10
不认为这是一个问题。 – 2013-03-10 21:15:17
当然,你不能将两个数组分配给一个变量。我测试了你的代码并整理了错误,并且在我测试的下面发布了一个答案,似乎工作得很好。 – adeneo 2013-03-10 21:22:04