AJAX是什么?
AJAX 是与服务器交换数据并更新部分网页的艺术,在不重新加载整个页面的情况下
XMLHttpRequest 对象
1.创建 XMLHttpRequest 对象 variable=new XMLHttpRequest();
2.向服务器发送请求 1.)xmlhttp.open(“GET”,“test1.txt”,true);
2.)xmlhttp.send();
3.服务器响应 如需获得来自服务器的响应,请使用 XMLHttpRequest 对象的 responseText 或 responseXML 属性
responseText 属性
如果来自服务器的响应并非 XML,请使用 responseText 属性。
responseText 属性返回字符串形式的响应,因此您可以这样使用:
document.getElementById(“myDiv”).innerHTML=xmlhttp.responseText;
4.onreadystatechange 事件
当请求被发送到服务器时,我们需要执行一些基于响应的任务。
每当 readyState 改变时,就会触发 onreadystatechange 事件。
readyState 属性存有 XMLHttpRequest 的状态信息。
下面是 XMLHttpRequest 对象的三个重要的属性:
onreadystatechange 存储函数(或函数名),每当 readyState 属性改变时,就会调用该函数。
readyState
存有 XMLHttpRequest 的状态。从 0 到 4 发生变化。
0: 请求未初始化
1: 服务器连接已建立
2: 请求已接收
3: 请求处理中
4: 请求已完成,且响应已就绪
status
200: “OK”
404: 未找到页面
在 onreadystatechange 事件中,我们规定当服务器响应已做好被处理的准备时所执行的任务。
当 readyState 等于 4 且状态为 200 时,表示响应已就绪:
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
jq的ajax
方法一: $.ajax(url,data,fn);
方法二:$.post(URL,data,callback);
方法三:$.get(url,callback);
$.ajax({
url:"112.json",
type:"post",
data:{
//传递参数
},
success:function(res){//res表示是否与服务器连接成功
console.log(res);//json中的数据
if (res.status == 'ok') {//当状态为ok时,显示json中的数据
console.log(res.datas[0].name);
}else{
alert('没有相关数据');
}
},
error:function(e){
// 抛弃异常
}
});
$.post("112.json",{
"activeName":activeName,
"sels":sels,
"end":end
},function(res){
if (res.message == '0') {
alert('成功');
// 向tbody中添加数据
}
});
$.get("112.json",function(res){
if (res.status == 'ok') {
alert('成功');
// 向tbody中添加数据
}
});
axios
get请求axios.get(url[, config])
post请求axios.post(url[, data[, config]])
通用请求axios(config)
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// 可选地,上面的请求可以这样做
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
axios({
methods: 'post',
url: 'http://jsonplaceholder.typicode.com/users',
data: {
name: 'qiurx'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})