前后端json标记约定
{
“success": true, 请求是否成功
"errormsg" : "xxx ", success为false的时候返回信息
"data" : "xxx", 返回的数据
}
客户端处理json字符串代码优化
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
document.getElementById('search').onclick=function () {
// 发送Ajax查询请求并处理
var request = new XMLHttpRequest();
request.open("GET","service.php?number="+document.getElementById('keyword').value)
request.send();
request.onreadyState =function () {
if (request.readychangeState === 4) {
if (request.status === 200) {
var data = JSON.parse(request.responseText);
if (data.success) {
document.getElementById("searchResult").innerHTML = data.msg;
}else{
document.getElementById("searchResult").innerHTML =
"出现错误:" + data.msg;
}
document.getElementById("searchResult").innerHTML = request.responseText;
}else{
alert("发生错误:" + request.status);
}
}
}
}
document.getElementById('save').onclick=function () {
// 发送Ajax查询请求并处理
var request = new XMLHttpRequest();
request.open("POST","service.php");
var data = "name=" + document.getElementById("staffName").value
"&number=" + document.getElementById("staffNumber").value
"&sex=" + document.getElementById("staffSex").value
"&job=" + document.getElementById("staffJob").value
request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
request.send(data);
request.onreadyState =function () {
if (request.readychangeState === 4) {
if (request.status === 200) {
var data = JSON.parse(request.responseText);
if (data.success) {
document.getElementById("createResult").innerHTML = data.msg;
}else{
document.getElementById("createResult").innerHTML =
"出现错误:" + data.msg;
}
document.getElementById("createResult").innerHTML = request.responseText;
}else{
alert("发生错误:" + request.status);
}
}
}
}
</script>
</body>
</html>
通常我们不用原生的js写页面,而是用js库,比如jquery
http://apps.bdimg.com/libs/jquery/1.11.1/jquery.js这是一个在线的jquery资源库
jQuery改造ajax
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/1.11.1/jquery.js">
$(document).ready(function () {
$("#search").click(function () {
$ajax({
type: "GET",
url:"service.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:"service.php",
dataType:"json",
data{
name:$("#staffName").val(),
number:$("#staffNumber").val(),
sex:$("#staffsex").val(),
job:$("#staffjob").val(),
},
success:function (data) {
if (data.success) {
$("#createResult").html(data,msg);
}else{
$("#createResult").html("出现错误:"+ data.msg);
}
},
error:function (jqXHR) {
alert("发生错误:"+ jqXHR.status);
}
});
});
</script>
</body>
</html>