Ajax介绍:
以前前端获取后端服务器传过来的数据,还要再JS中先new一个XmlHttpRequest对象非常麻烦,现在我们引入Jquery,
直接在前端使用Jquery的$.ajax()方法,然后通过function函数的result参数,就可以异步获取后端服务器的数据。
ajax: 异步通信技术的一种实现;
不刷新页面的情况下,客户端浏览器网页可以跟服务器后天进行数据交换;
1、触发一个js事件(单击、键盘、change、blur、focus.....)
2、调用jQuery的ajax方法
jQuery.post(url, [data], [callback], [type])
url:发送请求地址。
data:待发送 Key/value 参数。
callback:发送成功时回调函数。
type:返回内容格式,xml, html, script, json, text, _default。
3、编写服务器的代码,完成ajax需要的功能,并通过io输出数据;
out.print(返回数据字符串);
4、jQuery的ajax方法处理回调函数的业务(callback方法)
<html>
<head>
<title>here</title>
<!-- 引入 jquery -->
<script type="text/javascript" src="js/jquery-3.6.3.min.js"></script>
<script type="text/javascript">
$(function() {
$("#dep").on("change", getPerson);
})
function getPerson() {
// 第一种模板
$.ajax({
url:"ajax_info.txt" ,
type:"get" ,
data:"name=zs",
success:function(result, textStatus){
alert("成功");
console.log(result)
},
error:function(xhr,errorMessage,e){
alert("失败");
}
});
//第二种模板
$.get(
"ajax_info.txt" ,
"name=zs",
function(result, textStatus,xhr){
alert("成功!!!!!");
}
);
//第三种模板
$.post(
"ajax_info.txt" , // 目前我们没有搭建后台服务器,并且请求的是 文件形式。此种情况只能使用 get
"name=zs",
function(result, textStatus,xhr){
alert("成功!!!!!");
}
);
//第四种模板
请求 ajax_info.txt ,将返回值 赋值给 persons 元素
$("#persons").load(
"ajax_info.txt"
);
}
</script>
</head>
<body>
<select id="dep"></select>
<div id="persons"></div>
</body>
</html>
第一种模板:
$.ajax({
url:"url请求地址" ,
type:"请求方式(“get”,“post”)" ,
data:"参数传递",
success:function(result, textStatus){
alert("成功");
console.log(result)
},//请求成功执行success函数
error:function(xhr,errorMessage,e){
alert("失败");
}//失败执行error函数
});
第二种模板:
$.get(
"url请求地址",
"参数传递",
function(result, textStatus,xhr){
alert("成功!!!!!");
}//成功函数
);
第三种模板:
$.post(
"ajax_info.txt" , // 目前我们没有搭建后台服务器,并且请求的是 文件形式。此种情况只能使用 get
"参数传递",
function(result, textStatus,xhr){
alert("成功!!!!!");
}//成功函数
);
第四种模板:
$("#persons").load(
"ajax_info.txt"
);// 请求 ajax_info.txt ,将返回值 赋值给 persons 元素