【问题标题】:Using AJAX to call PHP file to return database results via JSON and populate a selection box使用AJAX调用PHP文件通过JSON返回数据库结果并填充选择框
【发布时间】:2015-06-30 19:21:38
【问题描述】:

我目前是一名学生,所以请意识到我的技能是非常新的(对于所有 HTML、CSS、Javascript、PHP 等,实际上只有几个月的时间)。我正在为一个 PHP 课程做一个学校项目,以及一些我想做的事情,超出了我迄今为止所学的范围(JSON 和 AJAX 对我来说是全新的)。这将是我在这个网站上的第一篇文章,尽管在过去几个月里我经常将其用作参考。

我的目标是创建一个网站,其中包含来自名为“make”的 MySQLi 数据库表中的汽车制造商的下拉框(选择框)。一旦您选择了汽车“制造商”,那么第二个下拉框应该会启用并填充所选制造商的相关型号。此模型信息来自同一数据库中名为“model”的另一个表。

“make”表的结构如下:

插入makeidcodetitle)值 (1,“讴歌”,“讴歌”), (2,“阿尔法”,“阿尔法罗密欧”), (3, 'AMC', 'AMC'), (4,“阿斯顿”,“阿斯顿马丁”), (5, '奥迪', '奥迪'), (6,“阿凡提”,“阿凡提”), (7, 'BENTL', '宾利'), (8, '宝马', '宝马'), (9, '别克', '别克'), (10, 'CAD', '凯迪拉克'), (11, 'CHEV', '雪佛兰'), (12, 'CHRY', '克莱斯勒'), (13, 'DAEW', '大宇'), 等等

“模型”表如下所示:

插入modelidmake_idcodetitle)值 (1, 1, 'CL_MODELS', 'CL 模型 (4)'), (2, 1, '2.2CL', '- 2.2CL'), (3, 1, '2.3CL', '- 2.3CL'), (4, 1, '3.0CL', '- 3.0CL'), (5, 1, '3.2CL', '- 3.2CL'), (6, 1, 'ILX', 'ILX'), (7, 1, 'INTEG', 'Integra'), (8, 1, '传奇', '传奇'), (9, 1, 'MDX', 'MDX'), (10, 1, 'NSX', 'NSX'), (11, 1, 'RDX', 'RDX'), (12, 1, 'RL_MODELS', 'RL 模型 (2)'), (13, 1, '3.5RL', '- 3.5 RL'), (14, 1, 'RL', '-RL'), (15, 1, 'RSX', 'RSX'), (16, 1, 'SLX', 'SLX'), (17, 1, 'TL_MODELS', 'TL 模型 (3)'), 等等

我有从数据库表“make”中填充第一个保管箱的代码就好了。一旦您从 Dropbox(onchange 事件)中选择了一个品牌,它似乎正在调用我的 javascript 函数,因为我可以提醒该品牌并且它显示正常。之后它不起作用。我不确定它是否正确调用了我的 php 代码,php 是否正常工作等。请查看并告诉我您的想法!

这是我的两个 Dropbox 的 HTML 和 Javascript 函数:

<script>
function getModel(carMake)
{
  var xmlhttp;
  var getRequest;
  alert(carMake); //This alert is working and shows car make!
  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)
    {
	  var carModels = JSON.parse(xmlhttp.responseText).split(' ');
	  alert (carModels.toString());
	  var carModelsHTML = "";
	  for (i=0; i < carModels.length; i++)
	  {
		carModelsHTML += "<option value=\"" + carModel[i] + "\">" + carModel[i] + "</option><br/>";
	  }
	  alert(carModelsHTML);
	  document.getElementById("vehicle_model").disabled = false;
      document.getElementById("AjaxDiv").innerHTML = carModelsHTML;
    }
  }
  
getRequest = "myAjax.php?make="+carMake;
xmlhttp.open("GET",getRequest,true);
xmlhttp.send();
}
</script>
Vehicle Make:

<select name="vehicle_make" value="<? echo $_SESSION['vehicle_make']?>" required onchange="getModel(this.value)">
<?
	$sql = "SELECT * FROM make"; // Build an MySQLi statement to select the makes of all MFGs
	$result = mysqli_query($mysqli, $sql); // Perform the MySQLi query on the database to get the filename.
						
	while($row = mysqli_fetch_assoc($result)) //while we haven't the end of the list of MFGs
	{
	?>
      <option value="<? echo $row["title"] ?>"><? echo $row["title"] ?></option>
    <?
	}

					
?>
</select>

<br/>

Vehicle Model:

<select name="vehicle_model" value="<? echo $_SESSION['vehicle_model']?>" required disabled>
	<div id="ajaxDiv">
					<!-- Javascript placeholder for getModel function -->
	</div>
</select>

这是我的 PHP 文件 - 我不确定是否需要再次包含我的数据库连接文件,我假设不需要,但在代码不起作用时尝试了它。

<?
include "database.php";

$value = $_REQUEST["make"];

$sql = "SELECT * FROM make WHERE title=" . $value; // Build an MySQLi statement to select the corresponding make of car
$result = mysqli_query($mysqli, $sql); // Perform the MySQLi query on the database
$makeID = mysqli_fetch_assoc($result);


$sql = "SELECT * FROM model WHERE id=" . $makeID["id"]; //Now cross reference the models of car for that manufacturer using the corresponding id from the "make" table.
$result = array(); //Reset the $result array to be reused.
$result = mysqli_query($mysqli, $sql); //Perform the data collection from the model table of the database

while($row = mysqli_fetch_assoc($result)) 
{
	$models = $row["title"] . " ";
}
trim($models); //The last entry will have an extra space on the end, in order not to create encoding issues we will trim it off.
$data = json_encode(array("models" => $models)); //Encode all the models from the string we created into an object so we can send it back to the javascipt on the client side.
echo $data; //By echoing out the object at the end we are passing the encoded data back to the javascript on the other side.

?>

【问题讨论】:

  • 您确实需要缩小问题范围。巨大的代码墙使得有人能够帮助您的可能性大大降低。
  • 对不起,我有一个有点详细和啰嗦的习惯。不幸的是,不知道问题出在哪里,并且在尝试了我知道的有限调试后被卡住了,这导致我在这里发布所有相关代码并尝试寻求帮助。

标签: php ajax json dynamic drop-down-menu


【解决方案1】:

我真的建议你先看看这个:

http://www.w3schools.com/php/php_ajax_intro.asp

我认为你会学到很多东西。

【讨论】:

  • 感谢您的评论,我已经来过这里了。我已经从头到尾完成了 w3schools 关于 ajax 的“课程”,并且大部分 php 也已经完成。我还在这个网站上搜索了一个解决方案,并收集了我能找到的相关代码。再说一次,我是一个初学者,但我已经尽可能多地用谷歌搜索了。我只是想找人快速查看我的代码并指出问题出在哪里的正确方向。我会从那里去。
  • 要调试漏洞,我建议从服务器端开始。将一些调试输出放入您的 php 代码中,并根据需要向 url 添加 GET 数据直接调用 php 页面。所以所有的调试都会直接打印到浏览器窗口。
  • 例如回显 $makeid 和每个 $row 当然用空格。最后可能是 $data 。然后在浏览器窗口中调用 yourphpfile.php?make=anyid
  • 这是个好主意。我会试试的。谢谢你的建议。我的大脑充满了来自搜索等的新信息。我知道我错过了一些明显的东西......这正是我来到这里的原因! :)
【解决方案2】:

通过 Jonathan 提供的调试想法,我能够取得一些进展并最终让它工作。请注意,对原始帖子中的代码进行了相当多的更改,但希望这将有助于其他可能陷入类似问题或来自这篇文章的人......

现在是 Javascript 和 HTML:

<script>
function getModel(carMake)
{
var xmlhttp;
var getRequest;

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)
    {
		var carModels = xmlhttp.responseText.split(','); //Receive the car models in one long string with each seperated by a ',' and split it up into an array
		
		//Below section of code grabs the current "model" dropbox and finds the length, then nulls all options.
		var currentOptions = document.getElementById("vehicle_model");
		for (i = currentOptions.options.length-1; i >=0; i--)
		{
			currentOptions.remove(i);
		}
		
		//Below goes through all the model options just returned from the database and populates the "model" dropbox again.
		for (i=0; i < carModels.length; i++)
		{
			var newOption = document.createElement("option");
			newOption.text = carModels[i];
			newOption.value = carModels[i];
			var dropDown = document.getElementById("vehicle_model");
			try
				{
					dropDown.add(newOption, null); //This is for all browsers except old IE
				}
				catch(ex) //If an exception occurs and the option refuses to add then try IE option below
				{
					dropDown.add(newOption); //For older versions of IE
				}
		}
    }
  }
getRequest = "myAjax.php?make="+carMake;
xmlhttp.open("GET",getRequest,true);
xmlhttp.send();
}
</script>
Vehicle Make:

<select id="vehicle_make" value="<? echo $_SESSION['vehicle_make']?>" required onchange="getModel(this.value)">
<?
	$sql = "SELECT * FROM make"; // Build an MySQLi statement to select all MFGs in database
	$result = mysqli_query($mysqli, $sql); // Perform the MySQLi query on the database.
						
	while($row = mysqli_fetch_assoc($result))
	{
?>
        <option value="<? echo $row["title"] ?>"><? echo $row["title"] ?></option>
      <?
    }
      ?>
</select>
<br/>

Vehicle Model:

<select id="vehicle_model" value="<? echo $_SESSION['vehicle_model']?>" required>
</select>

那么这里是PHP代码:

<?
include "database.php"; //connects to the MySQLi database - $mysqli
$value = $_REQUEST["make"];


$sql = "SELECT * FROM make WHERE title='" . $value . "'"; // Build an MySQLi statement to select the filename from the users table using the ID for reference.
$result = mysqli_query($mysqli, $sql); // Perform the MySQLi query on the database to get the filename.
$makeID = mysqli_fetch_assoc($result); // Put data gathered into $makeID


$sql = "SELECT * FROM model WHERE make_id=" . $makeID["id"]; //Now cross reference the models of car for that manufacturer using the corresponding id from the make table.

$result = array(); //Reset the $result array to be reused.
$result = mysqli_query($mysqli, $sql); //Perform the data collection from the model table of the database

while($row = mysqli_fetch_assoc($result)) //For each model found this will build one string into $models with each seperated by a ','
{
	$models = $models . $row["title"] . ",";
}

$models = trim($models, ","); //The last entry will have an extra ',' on the end, to avoid future issues we will trim it off.

echo $models; //By echoing out the string we are passing it back to the javascript

?>

然后就做到了!感谢调试课。这就是我朝着正确方向前进所需要的一切。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-24
    • 2020-08-26
    • 1970-01-01
    相关资源
    最近更新 更多