Ajax——原生Js实现和Jquery实现
什么是AJAX?
AJAX = 异步 JavaScript 和 XML。
AJAX 是一种用于创建快速动态网页的技术。
通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
下面通过原生JavaScript和Jquery库实现
AJAX的请求是是需要后台配合的,在实现的时候可能会出现跨域的问题(本次提前解决了跨域问题)
原生Js实现
html
<style>
#res{
height: 300px;
width: 300px;
border: red solid 5px;
}
</style>
<button>点击发送请求</button>
<!-- #res标签存放ajax响应体 -->
<div id="res"></div>
Javascript
let btn = document.getElementsByTagName("button")[0];
let res = document.getElementById('res');
btn.onclick = function(){
//创建对象
let xhr = new XMLHttpRequest();
//设置请求方式
//GET方法
xhr.open('GET', 'www.****.com');
//get传参:xhr.open('GET', 'www.****.com?a=100&b=200');
//POST方法
//xhr.open('POST', 'www.****.com')
//post传参是直接在xhr.send()中传。eg:xhr.send('a=100&b=200')
//设置请求头
xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
//发送
xhr.send();
//处理返回结果
xhr.onreadystatechange = function(){
//readyState 是XMLHttpRequest对象中的属性,共有5个值 0 1 2 3 4 表示状态
//0 表示未初始化,readyState的初始值
//1 表示open()方法调用完毕
//2 表示send()方法调用完毕
//3 表示服务端返回了部分数据
//4 表示服务端返回了所有数据
if(xhr.readystate === 4){
if(xhr.status >= 200 && xhr.status < 300){
//xhr.responseText、xhr.response.URL都可以自己打印尝试
res.innerHTML = xhr.response
}
}
}
}
Jquery实现
html
<button class="col-3">GET</button>
<button class="col-3">POST</button>
<button class="col-3">AJAX</button>
javascript
//get方法
$('button').eq(0).click(function(){
$.get('www.****.com', {a: 100}, function(data){
console.log(data);
})
})
//post方法
$('button').eq(1).click(function(){
$.post('www.****.com', {a: 100}, function(data){
console.log(data);
})
})
// POST\GET都可
$('button').eq(2).click(function(){
$.ajax({
type: 'get',
url: 'www.****.com',
data:{
a: 100,
b:200
}
success: function(data){
console.log(data);
},
error: function(data){
console.log('请求失败')
}
})
})

浙公网安备 33010602011771号