ajax通用格式:
$(function(){
//请求参数
var list = {};
//
$.ajax({
//请求方式
type : “POST”,
//请求的媒体类型
contentType: “application/json;charset=UTF-8”,
//请求地址
url : “http://127.0.0.1/admin/list/”,
//数据,json字符串
data : JSON.stringify(list),
//请求成功
success : function(result) {
console.log(result);
},
//请求失败,包含具体的错误信息
error : function(e){
console.log(e.status);
console.log(e.responseText);
}
});
});
记录本人第一次写ajax接口,用循环count来计算总人数,其实可以arr.length。以下是示例。
html:
<ul id="leftp">
</ul>
<table class="centerup1">
<tr align="middle">
<td>
<p>迟到人数</p>
</td>
<td>
<p>总人数</p>
</td>
<tr align="middle" >
<td id="span1"></td>
<td id="span2"></td>
</table>
<table class="centerup2" >
<tr align="middle">
<td>
<p>迟到率</p>
</td>
<tr align="middle">
<td id="span4"></td>
</table>
$(function() {
var count=0; //总人数
var count2=0;//迟到人数
//总人数
$(function() {
$.ajax({
url: './zongrenshu ',
type: 'get',
async: true,
success: function(res) {
$.each(res, function(i, ls) {
//获得数据如果string类型,需要 JSON.parse(res),f分解成数组,一行一行。
console.log(res)
#这里添加一行span
html = '<span>' + ls.count + '人' + '</span>';
count = ls.count;
$('#span2').append(html);
})
}
})
})
//迟到
$(function() {
$.ajax({
url: './chidao',
type: 'get',
async: true,
success: function(res) {
console.log(res)
$.each(res, function(i, ls) {
#这里是ul列表,添加li,包含图片和名字。
html = '<li>' +
'<img src="./static/facelib/' + ls.userphoto + '" />' +
'<p> ' + ls.fullname + '</p>' +
'</li>';
$('#leftp').append(html);
count2++;
})
html2 = '<span>' + count2 + '人' + '</span>';
$('#span1').append(html2);
//计算迟到率
percent1 = (count2 / count)*100;
percent1 = percent1.toFixed(1); #保留一位小数点
html3 = '<span>' + percent1 + '%' + '</span>';
$('#span4').append(html3);
}
})
})