我試圖使用AJAX,以便在下拉菜單(模塊標題)中選擇一個選項時,它將使用該值,使用該模塊標題對數據庫中的所有記錄執行SQL查詢,然後發佈與模塊標題相關的模塊代碼,即模塊標題:團隊項目=模塊代碼:11COB290。AJAX返回選擇框的值
繼承人的啓動代碼:
<td align="center">
<select name='ModuleTitle' id='ModuleTitle' onChange='select_code()' style='width:100%;'>
<option>Select...</option>
<?php
//3. Perform database query
$result = mysql_query("SELECT * FROM Module
ORDER BY `ModTitle` ASC;", $connection);
if(!$result){
die("Database query failed: " . mysql_error());
}
//4. Use Returned Data
while ($row = mysql_fetch_array($result)) {
$module = $row[2];
echo "<option name='{$module}'>{$module}</option><br />";
}
?>
</select>
</td>
<td align="center">
<span id="result"></span>
</select>
</td>
然後繼承人的.js文件:
var xmlhttp;
// Give the function a unique name, this is what your HTML will call to run the AJAX
function select_code() {
// This is all just setting up the variable, ignore it
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("result").innerHTML = xmlhttp.responseText;
}
};
var val = document.getElementById("ModuleTitle");
var title = val.options[val.selectedIndex].text;
var parameters = "title="
+ title;
xmlhttp.open("POST", "ajaxexample2mod.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(parameters);
}
和最終的PHP文件(ajaxexamplemod.php):
<?
<?php require_once("includes/connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php include("includes/headsec.php"); ?>
<?php
$title = $_POST['title'];
//3. Perform database query
$result = mysql_query("SELECT * FROM Module
WHERE ModTitle = {$_POST['title']}
ORDER BY `ModTitle` ASC;", $connection);
if(!$result){
die("Database query failed: " . mysql_error());
}
//4. Use Returned Data
while ($row = mysql_fetch_array($result)) {
$module = $row[3];
echo $module;
}
?>
酷!你有什麼問題? – 2012-02-26 00:05:51
它不返回我需要的數據,它不會迴應它 – ScottD 2012-02-26 00:07:25
嘗試做: alert(xmlhttp.responseText); 而不是:document.getElementById(「result」)。innerHTML = xmlhttp.responseText; 這會讓你知道PHP控制器是否正確回覆。如果你沒有任何警報意味着它可能是一個「連接」問題。嘗試還:alert(xmlhttp.readyState +「」+ xmlhttp.status)查看返回的代碼是什麼。這將幫助我們識別您的問題。 – Kursion 2012-02-26 12:33:54