项目一:二级联动菜单实现
jQuery对ajax的支持
1、jQuery对ajax进行封装,提供了$.ajax();
2、语法:$.ajax(options); – 传入json对象
常用设置项及说明
1、url 发送请求地址
2、type 请求类型get | post
3、data 向服务器传递的参数
4、dataType 服务器响应的数据类型 text | json | xml | HTML | jsonp | script
5、success 接受响应时的处理函数
6、error 请求失败时的处理函数
案例执行步骤
1、准备后台数据
2、准备前端页面
– Ajax文件下新建前端页面
3、对于json中的data参数遇到多个,怎么写?
(1) 第一种方式:字符串拼接 – “data”:”t=pypl&abc=123&uu=777”,
(2) jquery为我们提供了json的书写方式 – “data”:{“t”:“pypl”,“abc”:“123”,“uu”:“777”},
参考之前年月日的三级联动
实现效果
项目部分源代码
$(function(){
$.ajax({
"url":"http://localhost:8080/channel",
"data":{"level":"1"},
"type":"get",
"dataType":"json",
"success":function(json){
console.log(json);
for(var i=0;i<json.length;i++){
var ch = json[i];
$("#lv1").append("<option value='"+ ch.code +"'>"+ ch.name +"</option>");
}
}
})
})
$(function(){
$("#lv1").on("change",function(){
var parent = $(this).val();
console.log(parent);
$.ajax({
"url":"http://localhost:8080/channel",
"data":{"level":"2","parent":parent},
"dataType":"json",
"type":"get",
"success":function(json){
console.log(json);
//移除lv2下的所有原始options项
$("#lv2>option").remove();
for(var i=0;i<json.length;i++){
var ch = json[i];
$("#lv2").append("<option value='"+ ch.code +"'>"+ ch.name +"</option>");
}
}
})
})
})
项目二:登录案例 – 联动后端服务器
使用Ajax进行前后台的联动
案例执行步骤
1、准备user用户数据
去除两端空格 – $.trim() – 这个函数表示去除字符串两端的空白字符
2、新建ajax.html页面
(1) 登陆失败
(2) 登陆成功
(3)url地址、请求类型不匹配。服务器异常;
项目部分源代码
$.ajax({
url:"http://localhost:8080/ajax11",
data:{
username:username,
password:password
},
type:"post",
dataType:"json",
async:true,//false使用同步,true表示异步
success:function(req){
if (req.success==1) {
console.log(req.user);
alert('登陆成功!');
$(location).attr('href','index.html');
} else {
alert('登录失败!');
$(location).attr('href','user.html');
}
},
error:function(xmlHttp,errorText){
console.log(xmlHttp);
console.log(errorText);
alert("请求异常,请联系管理员解决!");
$(location).attr('href','user.html');
}
})