Ajax基本概念
Ajax(Asynchronous JavaScript And XML),异步 JavaScript 和 XML,用于异步请求数据,在不刷新网页的情况下更新页面数据,提升用户体验
Ajax优缺点
优点:
- Ajax最大的优点就是能在不刷新整个页面的情况下维持与服务器通信
- 使用异步的方式与服务器通信,不打断用户的操作
- 可将一些后端的工作移到前端,减少服务器与带宽的负担
- Ajax使得界面与应用分离,也就是数据与呈现分离
缺点:
- Ajax干掉了Back与History功能,即对浏览器机制的破坏,在动态更新页面的情况下,用户无法回到前一页的页面状态,因为浏览器仅能记忆历史纪录中的静态页面
- AJAX技术给用户带来很好的用户体验的同时也对IT企业带来了新的安全威胁,Ajax技术就如同对企业数据建立了一个直接通道。这使得开发者在不经意间会暴露比以前更多的数据和服务器逻辑
- 对搜索引擎支持较弱
JQuery中的Ajax使用实例
$.ajax()方法
$(function(){
$('#send').click(function(){
$.ajax({
type: "GET",
url: "test.json",
data: {username:$("#username").val(), content:$("#content").val()},
dataType: "json",
contentType: "application/x-www-form-urlencoded"
async: true,
cache: true,
timeout: 5000,
success: function (data) {},
error: function () {},
complete: function () {}
});
});
});
参数解释
- url String类型,请求的地址
- type String类型,请求方式,一般为get或者post请求,但是http的其他请求当然也可以
- timeout
- async Boolean类型,是否异步,默认设置为true,所有请求均为异步请求。如果需要发送同步请求,设置为false
- cache Boolean类型,是否从浏览器缓存中加载请求信息,默认为true,表示会从浏览器缓存中加载请求信息
- data Object或者String类型,发送到服务器的数据。如果已经不是字符串,将自动转换为字符串格式
- dataType String类型,希望服务器返回的数据类型,如果不是,就转化为指定的数据类型,如果不指定,JQuery将自动根据http包mime信息返回responseXML或responseText,并作为回调函数参数传递。可用的类型如下:
- xml:返回XML文档,可用JQuery处理
- html:返回纯文本HTML信息;包含的script标签会在插入DOM时执行
- script:返回纯文本JavaScript代码。不会自动缓存结果。除非设置了cache参数。注意在远程请求时(不在同一个域下),所有post请求都将转为get请求
- json:返回JSON数据
- jsonp:JSONP格式
- text:返回纯文本字符串
8. beforeSend Function类型,表示发送数据之前,进行的操作,例如想在发送数据之前设置请求头
beforeSend: function(request) {
request.setRequestHeader("Header", "x-www-***");
},
9. contentType String类型,发送信息至服务器时,内容编码类型默认为"application/x-www-form-urlencoded"
10. dataFilter Function类型,过滤数据(预处理数据),例如时间格式的预处理等,2个参数,参数一:Ajax返回的原始数据,参数二:dataType
参数
dataFilter: function (data, type) {
return data
}
11. global Boolean类型,默认为true
,表示触发全局ajax
事件,改为false
则不会触发ajax
全局事件
12. success Function类型,请求数据成功回调,2个参数,参数一:必需,服务器返回后经过dataType
参数处理后的数据,参数二:可选,描述状态的字符串
success: function (data, dataStatus) {}
13. error Function类型,请求数据成功回调,3个参数,参数一:必需,XMLHttpRequest对象,参数二:必需,错误信息,参数三:可选,捕获的错误对象
error: function (XMLHttpRequest, status, error) {}
14. complete Function类型,只要请求数据完成就回调,不管成功不成功,2个参数,参数一:必需,XMLHttpRequest对象,参数二:可选,描述请求类型的字符串
complete: function (XMLHttpRequest, status) {}
15. jsonp String类型,在一个jsonp请求中重写回调函数的名字。该值用来替代在"callback=?"这种GET或POST请求中URL参数里的"callback"部分
16. username String类型,用于响应HTTP访问认证请求的用户名
17. password String类型,响应HTTP访问认证请求的密码
实例:
1.向后台接口传两个参数activityTemplateNo, uiStyleNo ,后台返回一个对象
function showRecentStyle(activityTemplateNo, uiStyleNo) {
<%--var activityTemplateNo = '${activityTemplateStyle.activityTemplateNo}';--%>
// alert("tempalte:" + activityTemplateNo);
// var uiStyleNo = $('#uiStyleNo').val();
// alert("style:" + uiStyleNo);
$.ajax({
type: "post", //请求方式
url: "/activity/activityTemplateStyle/getStyleInfo", //后台接口url
data: {
templateNo: activityTemplateNo, // 传递的参数
uiStyleNo: uiStyleNo
},
dataType: "json", // 返回数据类型
success: function (data) {
// if 返回的是List集合
/*
if(data.length == 0 || data == null || data == ''){
return;
}
for(int i = 0; i < data.length; i++){
var perTr= data[i];
document.getElementById('popUpImg').src = perTr.popUpsUrl; // 弹窗url
}
*/
alert("data:" + data);
if (data == null || data == '') {
return;
} else {
var styleInfo = data;
document.getElementById('popUpImg').src = styleInfo.popUpsUrl;
document.getElementById('adBannerImg').src = styleInfo.adBannerUrl;
}
},
error: function (date) {
console.log(date);
}
})
}
2.前段传递相关参数,后台保存
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/easyui/themes/bootstrap/easyui.css" />
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/easyui/themes/icon.css" />
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/easyui/demo/demo.css" />
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/easyui/themes/default/easyui.css">
<script type="text/javascript" src="${pageContext.request.contextPath}/easyui/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/script/Calendar3.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/easyui/jquery.easyui.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/easyui/layer/layer.js"></script>
<table class="easyui-datagrid" id="datagriddata" title="信息列表" style="width:100%;height:600px;"
data-options="rownumbers:true,
singleSelect:true,
collapsible:false,
url:'${pageContext.request.contextPath}/purchaseverify/informationlist',
method:'get',
toolbar: '#tb',
pagination:true,
pageSize:20,
pageList:[10,20,30,50,80,100,200]">
<thead>
<tr>
<th data-options="field:'product'">product</th>
<th data-options="field:'areaname'">areaname</th>
<th data-options="field:'amount'">amount</th>
<th data-options="field:'phone'">phone</th>
<th data-options="field:'updateTime'" formatter="formatDatebox2">updateTime</th>
<th data-options="field:'createTime'" formatter="formatDatebox2">createTime</th>
</tr>
</thead>
<tbody></tbody>
</table>
<div id="button">
<button type="button" class="btn btn-primary" style="margin-right:40px;" onclick="comeBack()">
返回
</button>
<button type="button" class="btn btn-primary" style="margin-right:40px;" onclick="saveInformation()">保存更改</button>
<button type="button" class="btn btn-primary" style="margin-right:40px;" onclick="removeRecord()" >移除信息</button>
</div>
function formatDatebox2(value) {
if (value == null || value == '') {
return '';
}
var dt;
if (value instanceof Date) {
dt = value;
} else {
dt = new Date(value);
}
return dt.format("yyyy-MM-dd hh:mm"); //扩展的Date的format方法(上述插件实现)
}
function saveInformation(){
var rows = $('#datagriddata').datagrid('getSelections');
var item = rows[0];
var id = item.id;
var productList = [];
var formatList = [];
var amountList = [];
var linker = $("input[name ='linker']").val();
var phone = $("input[name ='phone']").val();
var area = item.areaname;
var province = $(".province>option:selected").text();
var city = $("select[name = 'city' ]").val();
$("input[name='product']").each(function () {
productList.push($(this).val());
});
$("input[name='productFormat']").each(function () {
formatList.push($(this).val());
});
console.log('formatList:'+formatList);
$(" input[name='amount']").each(function () {
amountList.push($(this).val());
});
var purchasestyle = $("input[name='purchasestyle']:checked").val();
var btime = $("#begintime").val();
var begintime ;
if (btime = "" || btime.length == 0){
begintime = new Date().format("yyyy-MM-dd ");
} else {
begintime = $("#begintime").val();
}
var etime =$("#endtime").val();
var endtime;
if (etime = '' || etime.length == 0){
endtime = '2090-12-31';
} else {
endtime = $("#endtime").val();
}
var dataParams=[]; dataParams.push({'id':id,'linker':linker,'phone':phone,'areaname':area,'product':productList,'productFormat':formatList,'amount':amountList,'purchaseStyle':purchasestyle,'beginTime':begintime,'endTime':endtime});
dataParams = JSON.stringify(dataParams);
$.messager.confirm('提示信息', "确定要保存吗?", function (r) {
if(r){
$.ajax({
url: "${pageContext.request.contextPath}/demo/save",
type: "post",
dataType: "json",
data:{"dataParams":dataParams} ,
success: function (data) {
if (data.code == "0") {
$.messager.confirm('提示信息', '保存信息成功!');
} else {
$.messager.confirm('提示信息', '保存信息失败!');
}
$("#datagriddata").datagrid("reload", jQuery("#datagriddata").serializeObject());
}
});
}
});
}
function validateRecord() {
var rows = $('#datagriddata').datagrid('getSelections');
if(rows.length!=1){
$.messager.alert('提示信息','请选择要核实的采购信息!');
return;
}
var id = rows[0].id;
var memberid = rows[0].memberid;
var source = rows[0].source;
$.messager.confirm('提示信息',"是否对该信息进行核实?",function(r){
if (r){
$.ajax({
url:"${pageContext.request.contextPath}/demo/shenhe",
type:"post",
dataType:"json",
data:{
"memberid":memberid,
"id":id,
"name":"<%=name %>",
"source":source
},
success:function(data){
if(data.code == "0"){
$.messager.alert('提示信息','变更成功');
}else{
$.messager.alert('提示信息','变更失败');
}
$("#datagriddata").datagrid("reload", jQuery("#datagriddata").serializeObject());
},
error:function(data){
console.log(data)
}
})
}
});
}