原生ajax和jquery中的ajax的使用和理解
Ajax 即“Asynchronous Javascript And XML”(异步 JavaScript 和 XML),是指一种创建交互式、快速动态网页应用的网页开发技术,无需重新加载整个网页的情况下,能够更新部分网页的技术。
通过在后台与服务器进行少量数据交换,Ajax 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
首先我们先用一个伪ajax来感受一下ajax的思想:
<body>
<div>
<p>请输入加载的地址:</p>
<p>
<input type="text" id="url" value="">
<input type="button" value="提交" onclick="loadPage()">
</p>
</div>
<div>
<h3>加载页位置</h3>
<iframe src="" id="target" width="48%" height="400px" name="iframe"></iframe>
</div>
</body>
<script type="text/javascript">
function loadPage() {
document.getElementById("target").src=document.getElementById("url").value;
}
</script>
效果:
原生(xhr)实现ajax:
<body>
<button type="button">点击发送请求</button>
</body>
<script type="text/javascript">
//原生ajax的使用
window.onload=function(){
//querySelector() 是 document.getdelementxx() 和 jquery 的 $("")选择器一样
var oBtn=document.querySelector("button");
/* 按钮添加事件 */
oBtn.onclick=function (){
//1.创建异步对象
var xml;
//ie兼容问题
if(window.XMLHttpRequest){
//chrome firefox safari ie7+
xml=new XMLHttpRequest();
}else{
//ie6
xml=new ActiveXObject("Micrisoft.XMLHTTP");
}
//2.设置请求
/* IE浏览器缓存 ajax如果访问地址一样不会实时显示 问题
Math.random();
new Date().getTime()
请求方式 请求地址 "index.html?t="+(new Date().getTime()) 是否异步true false */
xml.open("post","http://www.baoidu.com",true);
//发送表单数据
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");
//3.发送请求 psot请求 在send(写入发送的数据)
xml.send();
//4.处理返回的结果
xml.onreadystatechange = function(){
//判断是否请求完成
if(xml.readyState === 4){
alert(xml.status);
//判断请求后的返回状态码
if(xml.status >= 200 && xml.status < 300 || xml.status === 304){
//返回后台响应的 数据
console.log(xml.responseText);
console.log("接收到服务器返回的数据");
}else{
console.log("没有接收到服务器返回的数据");
}
}
}
}
}
</script>
Jquery封装的ajax使用(常用):
注:导入jquery的js文件
<head>
<title>Title</title>
<script src="${pageContext.request.contextPath}/static/js/jquery-3.4.1.min.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
用户名:<input type="text" id="name" onblur="a1()">
</body>
<script type="text/javascript">
function a1() {
$.ajax({
url:"${pageContext.request.contextPath}/ajax/a",
data:{"name":$("name").val()},
dataType:"json",
success:function (data,status) {
console.log(data);
console.log(status);
}
})
}
</script>
jquery还封装了:jquery.get() ,jquery.post()也是可以发送ajax异步请求的只不过是请求方式不同
后台处理ajax请求(SpringMvc):
@Controller
@RequestMapping("/ajax")
public class AjaxController {
@RequestMapping("/a")
public void ajax(String name, HttpServletResponse response) throws IOException {
if("yang".equals(name)){
response.getWriter().print("true");
}else{
response.getWriter().print("false");
}
}
}
浏览器效果: