Ajax
AJAX = Asynchronous JavaScript and XML(异步的 JavaScript 和 XML)。
AJAX 不是新的编程语言,而是一种使用现有标准的新方法。
AJAX 最大的优点是在不重新加载整个页面的情况下,可以与服务器交换数据并更新部分网页内容。
AJAX 不需要任何浏览器插件,但需要用户允许JavaScript在浏览器上执行。
Ajax使用
1、创建XMLHttpRequest对象
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else{
// IE6,IE5不支持XMLHttpRequest
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
2、向服务器发送请求
xmlhttp.open(method,url,async); // 规定请求的类型、URL、是否异步处理请求
xmlhttp.send(string); // 将请求发送到服务器 string仅支持post
xmlhttp.open("POST","/try/ajax/demo_post2.php",true); // post请求
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); // 设置请求头
xmlhttp.send("fname=Henry&lname=Ford"); // 发送的数据
3、服务器相应
xmlhttp.responseText; // 获取字符串形式的响应数据
xmlhttp.responseXML; // 获取XML形式的响应数据
4、onreadystatechange 事件
在 onreadystatechange 事件中,我们规定当服务器响应已做好被处理的准备时所执行的任务。
xmlhttp.onreadystatechange=function()
{
// 当 readyState 等于 4 且状态为 200 时,表示响应已就绪:
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
jquery ajax
$.ajax({
//请求方式
type : "POST",
//请求的媒体类型
contentType: "application/json;charset=UTF-8",
//请求地址
url : "http://127.0.0.1/admin/list/",
//数据,json字符串
data : JSON.stringify(list),
//请求成功
success : function(result) {
console.log(result);
},
//请求失败,包含具体的错误信息
error : function(e){
console.log(e.status);
console.log(e.responseText);
}
});
axios简单使用
// get请求
axios.get('xxx?id=1')
.then( res => {
console.log(res);
}).catch( err => {
console.log(err)
})
// 等价于
axios.get('xxx', {
params: {
id: 1
}
}).then( res => {
console.log(res);
}).catch( err => {
console.log(err)
})
// post请求
axios.post('xxx', {
aa: '',
bb: ''
}).then( res => {
console.log(res);
}).catch( err => {
console.log(err);
})