我想要一個用戶輸入一個國家,然後它會輸出它的人口。我的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