这是我第一次涉足 Javascript 和 AJAX(我正在阅读 JavaScript 和 JQuery,The Missing Manual)。我编写了这段代码来尝试使用 AJAX 将数据从表单发送到查询数据库的 php 文件(查询工作正常 phpMyAdmin),返回数据并使用 Javascript 在屏幕上显示以附加 div。
我的症结是让 AJAX 与服务器 php 页面一起工作。我还想知道是否可以采取一些步骤来检查我的代码是否正常工作。
这是我到目前为止写的内容,感谢您的帮助和见解:
<html>
<head>
<meta charset="UTF-8">
<title>Sidework Review Screen</title>
<link href="./_resources/_css/site.css" rel="stylesheet">
<script src="./_resources/_js/jquery-1.7.2.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
//var sw = "testing";
var sw = $("#switcher").val();
var tech = $("#id_techs option:selected").val();
// alert(tech);
$.post('side_work_controller.php',
{
switcher: sw,
id_techs: tech
},
function(data, status){
alert("Date: " + data + "\nStatue: " + status);
}); // end post
}); //end click
}); // end ready
</script>
</head>
<body>
<?php
try {
$username = "xxxx";
$password = "xxxx";
$dbh = new PDO('mysql:host=10.5.44.12;dbname=SideProjects', $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$sth = $dbh->prepare("SELECT DISTINCT tech_fname, tech_lname, extension
FROM `techs` ORDER BY tech_lname
");
$sth->execute();
$sql = $sth->fetchAll(PDO::FETCH_ASSOC);
?>
<div id="top"></div>
<div id="dropshadow"></div>
<div id="container">
<div id="left">
<div id="logo"><img src="logo.png"></div>
</div>
<div id="right">
<!--<form action="side_work_controller.php" name="switcher" method="post">';-->
<h1>Sidework Review</h1><p>
<label for="tech_ids"><h2>Choose a Technician</h2></label><p>
<select name="id_techs" id="id_techs"> //Builds drop down menu-->
<?php foreach ($sql as $row){
echo '<option value = "' . $row['extension'] . '">' . $row["tech_fname"] . ' ' . $row["tech_lname"] . ' - ' . $row['extension'] . '</option>';
} ?>
</select><p>
<input type="hidden" name="switcher" id="switcher" value="search">
<div id="button"><button>Review</button></div>
</div>
</div>
<div id="bottom"></div>
</body>
</html>
EDIT:
I've discovered that part of the problem is with my button, it needs to be
<button>Review</button> not
echo '<input type="submit" id="button" onclick="click()" value="Review">';
for this to work.
EDIT:
Also just worked out that the <select> and <input> tags needed id="[id name]" in order to work with the .val() function.
EDIT:
I've written a bit of the AJAX and is does send to the php file and gets some data.
I am reposting my changes for the benefit of newbie like me. The AJAX doesn't work correctly yet.