AJAX( Asynchronous Javascript and XML), is a web development technique for creating interactive web application. In conventional web applications, it transmits information to and from the server using synchronous requests. It means that when you fill out a form and submit, you will get directed to a new page with new informaiton from the server. With AJAX, when you transmit a part of information, it will make a request to server, interpret the results, and update the current page.
The process of Ajax request comprises of 4 stages:
<h1>员工查询</h1>
<label>请输入员工编号:</label>
<input type="text" id="keyword" />
<button id="search">查询</button>
<p id="searchResult"></p>
<h1>员工新建</h1>
<label>请输入员工姓名:</label>
<input type="text" id="staffName" /><br>
<label>请输入员工编号:</label>
<input type="text" id="staffNumber" /><br>
<label>请选择员工性别:</label>
<select id="staffSex">
<option>女</option>
<option>男</option>
</select><br>
<label>请输入员工职位:</label>
<input type="text" id="staffJob" /><br>
<button id="save">保存</button>
<p id="createResult"></p>
$(document).ready(function(){
$("#search").click(function(){
$.ajax({
type: "GET",
url: "http://127.0.0.1:8080/ajaxdemo/serverjson2.php?number=" + $("#keyword").val(),
dataType: "json",
success: function(data) {
if (data.success) {
$("#searchResult").html(data.msg);
} else {
$("#searchResult").html("出现错误:" + data.msg);
}
},
error: function(jqXHR){
alert("发生错误:" + jqXHR.status);
},
});
});
$("#save").click(function(){
$.ajax({
type: "POST",
url: "serverjson.php",
data: {
name: $("#staffName").val(),
number: $("#staffNumber").val(),
sex: $("#staffSex").val(),
job: $("#staffJob").val()
},
dataType: "json",
success: function(data){
if (data.success) {
$("#createResult").html(data.msg);
} else {
$("#createResult").html("出现错误:" + data.msg);
}
},
error: function(jqXHR){
alert("发生错误:" + jqXHR.status);
},
});
});
});
if ($SERVER["REQUESTMETHOD"] == "GET") { search(); } elseif ($SERVER["REQUESTMETHOD"] == "POST"){ create(); }
function search(){ if (!isset($GET["number"]) || empty($GET["number"])) { echo "参数错误"; return; }
global $staff;
$number = $_GET["number"];
$result = "没有找到员工。";
foreach ($staff as $value) {
if ($value["number"] == $number) {
$result = "找到员工:员工编号:" . $value["number"] . ",员工姓名:" . $value["name"] .
",员工性别:" . $value["sex"] . ",员工职位:" . $value["job"];
break;
}
}
echo $result;
}
function create(){ if (!isset($POST["name"]) || empty($POST["name"]) || !isset($POST["number"]) || empty($POST["number"]) || !isset($POST["sex"]) || empty($POST["sex"]) || !isset($POST["job"]) || empty($POST["job"])) { echo "参数错误,员工信息填写不全"; return; }
echo "员工:" . $_POST["name"] . " 信息保存成功!";
}