Ajax
Ajax(ASynchronous JavaScript And XML)
Ajax: 是一种在无需重新加载整个网页的情况下 能够更新部分网页的技术 通过在后台与服务器进行少量数据交换 Ajax可以使网页实现异步更新 这意味着可以在不重新加载整个网页的情况下 对网页的某部分进行更新 传统的网页(不使用Ajax)如果需要更新内容 必须重载整个网页页面 提升用户的体验
异步和同步:客户端和服务器端相互通信的基础上
同步:
客户端必须等待服务器端的响应
在等待的期间客户端不能做其他操作
异步:
客户端不需要等待服务器端的响应
在服务器处理请求的过程中
客户端可以进行其他的操作
原生Ajax发送GET请求
<body>
<button onclick="sendAjax()">GET请求</button>
</body>
<script>
function sendAjax(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "url", true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var jsonStr = xmlhttp.responseText;
var jsonObj = JSON.parse(jsonStr);
}
}
}
</script>
原生Ajax发送POST请求
<body>
<button onclick="sendAjax()">POST请求</button>
</body>
<script>
function sendAjax(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST','url', true);
xmlhttp.setRequestHeader('content-type','application/x-www-form-urlencoded');
xmlhttp.send('键=值','键=值');
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var jsonStr = xmlhttp.responseText;
var jsonObj = JSON.parse(jsonStr);
}
}
}
</script>
JQuery的方式发送Ajax的GET请求
<body>
<button>发送Ajax之get请求</button>
</body>
<script>
$('button').click(function() {
$.ajax({
'type': 'GET',
'url': 'http://wthrcdn.etouch.cn/weather_mini',
'data': {
"city": "商洛"
},
'success': function(respData) {
var date = respData.data.yesterday.date;
},
'error': function(errorData) {
alert("出错了")
},
'dataType': 'json'
});
});
</script>
JQuery的方式发送Ajax的POST请求
<body>
<button>发送Ajax之post请求</button>
</body>
<script>
$('button').click(function() {
$.ajax({
type: 'POST',
url: 'http://localhost:8080/login',
data: {
"username": "zhangsan",
"password": '123456'
},
contentType: 'application/x-www-form-urlencoded',
success: function(respData) {
console.log(respData);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("出错啦...")
},
'dataType': 'json'
});
});
</script>
简写Ajax请求
<body>
<button>发送Ajax之GET请求</button>
<button>发送Ajax获取后台返回的JSON数据</button>
<button>发送Ajax之POST请求</button>
</body>
<script>
$('button').first().click(function() {
$.get('url', function(respData) {
}, 'json');
});
$('button').last().click(function() {
$.post('http://localhost:8080/login', {
}, function(respData) {
}, 'json');
});
$('button').eq(1).click(function() {
$.getJSON('url', function(respData) {});
$.getJSON('http://localhost:8080/login', {
}, function(respData) {});
});
</script>
同源策略和跨域请求
同源策略:
浏览器出于安全考虑提出的这种策略
跨域:
协议相同 域名相同 端口号相同
浏览器才不受同源策略的影响
才可以正常的发送AJAX请求
解决跨域请求:
方案1: 在前端编写
JSONP:利用某些HTML标签他不受同源策略的限制
比如 img script
<img src="" alt="">
具体利用script标签来发送异步请求
来解除同源策略的限制
<script src=""></script>
缺点:只支持get请求
其他请求方式的跨域JSONP用不了
方案2: 在后端编写
cors
原生JS发送JSONP请求
callback=getJsonData 指定JSONP方式,回调的函数
JSONP的方式,后台在返回数据时,是这么放置的(JSON对象)
{"usename":"张三","password":"123456"}
JSONP的方式,那么后台返回的数据是这样
phone({"usename":"张三","password":"123456"})
<script type="text/javascript">
function phone(respData) {
console.log(respData);
}
</script>
<script src="https://www.baifubao.com/callback?cmd=1059&callback=phone&phone=15850781443">
</script>
JQuery发送JSONP请求
<body>
<button>发送JSONP请求</button>
</body>
<script>
$('button').click(function() {
$.ajax({
type: "GET",
url: "url",
jsonp: "callback",
success: function(res) {
console.log(res);
alert(res.data.area);
},
dataType: "jsonp"
});
});
</script>
练习–笑话大全

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>、
<style>
* {
margin: 0;
padding: 0;
}
body {
background-color: #7500b0;
}
#title {
font-size: 250%;
color: white;
margin-top: 5%;
text-align: center;
align: center;
}
hr {
margin-top: 3%;
}
button {
width: 13%;
height: 50px;
margin-left: 43.5%;
margin-top: 3%;
border: 0;
border-radius: 15px;
background-color: #410064;
font-size: 120%;
color: white;
line-height: 50px;
text-align: center;
}
button:hover {
cursor: pointer;
}
#content {
width: 60%;
height: 35px;
margin-left: 20%;
margin-top: 3%;
border: 0;
}
#content {
margin-left: 15%;
margin-top: 3%;
list-style: none;
width: 70%;
}
.c {
border: 1px #340053 solid;
height: 80px;
color: white;
text-align: left;
background-color: #50007c;
}
</style>
</head>
<body>
<div id="title">每日一笑</div>
<hr>
<button>来点段子</button>
<div id="content">
</div>
</body>
<script>
var btn = document.getElementsByTagName("button")[0];
btn.onclick = function() {
btn.innerHTML = "再来点";
var bigDiv = document.getElementById("content");
var smallDivs = document.getElementsByClassName("c");
if (smallDivs.length > 0) {
bigDiv.innerHTML = "";
}
var xmlhttp = new XMLHttpRequest;
xmlhttp.open("GET", "https://autumnfish.cn/api/joke/list?num=10", true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var jsonStr = xmlhttp.responseText;
var jsonObj = JSON.parse(jsonStr);
var datas = jsonObj.data;
for (let i = 0; i < datas.length; i++) {
var smallDiv = document.createElement("div");
smallDiv.setAttribute("class", "c");
bigDiv.appendChild(smallDiv);
var data = document.createTextNode(datas[i]);
smallDiv.appendChild(data);
}
}
}
}
</script>
</html>