好吧,所以我正在一個網站上有一個下拉菜單供用戶選擇一個學校名稱。一旦他們選擇了學校名稱,地址,郵編,縣和區域應該自動填充。使用AJAX填充HTML表單不工作的代碼?這是怎麼回事?
可悲的是,我其實是有這方面的工作僅僅幾個小時前,後來是我是誰,我愚蠢試圖完善我的代碼,但不保存的東西我有一個副本。現在形式人口不再有效。不過,我真的覺得我應該使用我的代碼。我很困惑。
可能有人請查看我的代碼,並告訴我,爲什麼它不工作?謝謝!
我的PHP代碼:
<?php
$searchtext = $_GET['name'];
$db = mysql_connect("localhost", "root", "");
if(!$db) {
die("Unable to connect to DB: " . mysql_error());
}
$useDB = mysql_select_db('hsmathcontest');
if (!$db) {
die("Use database failed: " . mysql_error());
}
$schoolID = mysql_query("SELECT ID,address,city,state,zip FROM schools WHERE name = \"$searchtext\"");
if (!$schoolID) {
die("Query failed: " . mysql_error());
}
$row = mysql_fetch_row($schoolID);
$ID = $row[0];
$addr = $row[1];
$city = $row[2];
$state = $row[3];
$zip = $row[4];
$county = mysql_query("SELECT ID,name FROM county WHERE schoolID = \"$ID\"");
if (!$county) {
die("Query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($county)) {
$countyID = $row[0];
$countyName = $row[1];
}
$district = mysql_query("SELECT ID,district FROM district WHERE ID = \"$countyID\"");
if (!$district) {
die("Query failed: " . mysql_error());
}
$row = mysql_fetch_array($district);
$districtID = $row[0];
$districtName = $row[1];
$fullAddress = $addr." ".$city." ".$state;
$data = $fullAddress . "," . $zip . "," . $countyName . "," . $districtName;
echo $data;
?>
我的Javascript代碼:
function populateForm() {
//get school chosen by user
var schoolSelected = document.getElementById("schoolName").value;
var XHR = new XMLHttpRequest();
XHR.open('GET', "lookup.php?name="+schoolSelected, true);
XHR.onreadystatechange = function(){
try {
if(XHR.readyState === 4 && XHR.status === 200) {
var data = XHR.responseText.split(",");
document.getElementById('address').innerHTML = data[0];
document.getElementById('zip').innerHTML = data[1];
document.getElementById('county').innerHTML = data[2];
document.getElementById('district').innerHTML = data[3];
}
}
catch (e) {
console.error('The server signalled a problem: ' + e.description);
}
}
XHR.send();
}
最後,形式本身,其中populateForm()函數的onchange呼籲:
<form name="register" method = "POST" action="<?PHP $_SERVER['PHP_SELF'] ?>">
If you have already registered please click <a href = "JavaScript:void(0);" onClick = "goToLogin();">here</a> to login to your account.<br />
*All fields required.*<br /><br />
School Name: * <select id = "schoolName" name = "schoolName" required onchange = "populateForm();">
<option></option>
那麼什麼是失敗,數據庫,PHP或JavaScript? – Steve
我不是100%確定。我知道當我的代碼工作時,所有3個都在工作。我真的不明白爲什麼它不再工作。我在想這是PHP或Javascript的東西,因爲我仍然可以連接到數據庫來獲得我的下拉菜單。 – RecursionIsSexy
好了,好了,如果你使用的是Chrome/Firefox的Firebug的,你可以看看JS錯誤在控制檯,你在哪裏傾倒例外 – Steve