我是 web 基础应用程序开发的新手,我正在学习 AJAX。这是我的问题,我正在尝试使用一些变量(用户输入)发出 AJAX 请求并获取具有相同变量的 php 文件。以下是我的代码,如果我遗漏了什么或者我做错了,请告诉我,我将不胜感激!谢谢你。
Javascript代码:
<script type="text/javascript">
function ajaxFunction(){
var ajaxRequest;
try{
ajaxRequest = new XMLHttpRequest();
}catch (e){
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
document.getElementById("Alert").innerHTML= "*Your browser broke!";
document.getElementById("Alert").style.color = '#E00000 ';
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('display');
ajaxDisplay.value = ajaxRequest.responseText;
}
}
var input_building = document.getElementById('building').value;
var input_room = document.getElementById('room').value;
var queryString = "?building=" + input_building + "&room=" + input_room;
ajaxRequest.open("GET", "map.php" + queryString, true);
ajaxRequest.send();
}
</script>
HTML:
<select id="building" name="building">
<option value="#" default >Select</option>
<option value="Luis C. Monzon">Luis C. Monzon</option>
</select>
<input type="text" id="room" name="room" placeholder="eg. 208B / CH 116" >
<input id="submit" type="button" value="submit" onclick="ajaxFunction()" >
<p id="display"></p>
PHP 文件:
<?php>
$building = $_GET['building'];
$room = $_GET['room'];
echo "<h1>".$room." ".$building."</h1>";
?>