XMLHttpRequest对象的常用方法和属性。
open(“method”,”URL”) 建立对服务器的调用,第一个参数是HTTP请求 方式可以为GET,POST或任何服务器所支持的您想调用的方式。第二个参数是请求页面的URL,第三个参数默认为true,传入false会使得请求变为同步阻塞模式。
send()方法,发送具体请求
abort()方法,停止当前请求
readyState属性 请求的状态 有5个可取值0=未初始化 ,1=正在加载 2=已加载,3=交互中,4=完成
responseText 属性 服务器的响应,表示为一个串
reponseXML 属性 服务器的响应,表示为XML
status 服务器的HTTP状态码,200对应ok 400对应not found
最原始版本的Ajax请求
// get 请求
function ajax(url,success,error){
var oAjax = new XMLHttpRequest();
oAjax.open('GET',url,true);
oAjax.send();
oAjax.onreadystatechange = function(){
if(oAjax.readyState == 4){
if(oAjax.status == 200){
success(oAjax.responseText); //成功的回调函数
}else{
error(oAjax.status); //失败的回调函
}
}
};
}
// post 请求
function ajax(url,success,error){
var oAjax = new XMLHttpRequest();
oAjax.open('POST ',url,true);
oAjax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
oAjax.send('fname=Bill&lname=Gates');
oAjax.onreadystatechange = function(){
if(oAjax.readyState == 4){
if(oAjax.status == 200){
success(oAjax.responseText); //成功的回调函数
}else{
error(oAjax.status); //失败的回调函数
}
}
};
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Ajax客户端</title>
<style type="text/css">
.result {
width: 300px;
height: 100px;
margin: 10px 0px 80px;
}
</style>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<div class="main">
<button id="Test1Button" value="我是原生Ajax" οnclick="send_GET()">Ajax异步请求</button>
<div class="result" style="background: cornflowerblue;" id="result1" />
</div>
<!--显示回调数据-->
<form style="background: greenyellow;" id="myForm">
请输入姓名:<input type="text" name="name" />
请输入年龄:<input type="text" name="age" />
<input type="button" value="发送表单数据" οnclick="sendForm();" />
<div class="result" id="result2"></div>
<!--显示回调数据-->
</form>
<button id="Test3Button" value="我是jQuery" οnclick="send_jQuery()">jQuery版本Ajax异步请求</button>
<div class="result" style="background: palevioletred;" id="result3" />
</div>
<!--显示回调数据-->
</div>
<script type="text/javascript">
//原生Ajax的GET基础操作
function send_GET() {
var Test1ButtonValue = document.getElementById("Test1Button").value; //获取按钮的值
var xhr = new XMLHttpRequest(); //创建XMLHttpRequest对象
xhr.onload = function (e) {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("result1").innerHTML = this.responseText;
}
};
xhr.open("GET", "Ajax服务端1.php?Test1ButtonValue=" + Test1ButtonValue, true);
xhr.send(null);
}
//原生Ajax的POST基础操作
function send_POST() {
var Test1ButtonValue = document.getElementById("Test1Button").value; //获取按钮的值
var xhr = new XMLHttpRequest(); //创建XMLHttpRequest对象
xhr.onload = function (e) {
if (xhr.status == 200) {
document.getElementById("result1").innerHTML = this.responseText;
}
};
xhr.open("POST", "Ajax服务端1.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8"); //必须要
xhr.send("Test1ButtonValue=" + Test1ButtonValue);
}
//原生Ajax发送表单
function sendForm() {
var form = document.getElementById("myForm");
var formData = new FormData(form);
formData.append('myData', '测试'); //可以添加数据
var xhr = new XMLHttpRequest(); //创建XMLHttpRequest对象
xhr.onload = function (e) {
if (xhr.status == 200) {
document.getElementById("result2").innerHTML = this.responseText;
}
};
xhr.open("POST", "Ajax服务端2.php", true);
xhr.send(formData);
}
//jQuery调用ajax
function send_jQuery() {
var Test3ButtonValue = document.getElementById("Test3Button").value; //获取按钮的值
$.ajax({
type: "POST",
data: {
Test3ButtonValue: Test3ButtonValue
},
url: "Ajax服务端3(jQuery).php",
// dataType:"json",//写成jsonp可实现跨域
success: callBack, //回调函数
async: true
});
}
//回调函数
function callBack(data) {
document.getElementById("result3").innerHTML = data;
}
</script>
</body>
</html>
<?php #Ajax服务端1.php
$Test1ButtonValue=$_REQUEST['Test1ButtonValue'];
echo "后端返回数据:",$Test1ButtonValue;
?>
<?php #Ajax服务端2.php
$name = $_POST['name'];
$age = $_POST['age'];
$myData = $_POST['myData'];
echo '服务器接收数据:<br/>';
echo '姓名:', $name, '<br/>';
echo '年龄:', $age, '<br/>';
echo '附加数据:', $myData;
?>
<?php #Ajax服务端3(jQuery).php
$Test3ButtonValue=$_REQUEST['Test3ButtonValue'];
echo "后端返回数据:",$Test3ButtonValue;
?>
Axios和Ajax的区别
axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端,本质上也是对原生XMLHttpRequest的封装,只不过它是Promise的实现版本,符合最新的ES规范,它本身具有以下特征:
1.从浏览器中创建 XMLHttpRequest
2.支持 Promise API
3.客户端支持防止CSRF
4.提供了一些并发请求的接口(重要,方便了很多的操作)
5.从 node.js 创建 http 请求
6.拦截请求和响应
7.转换请求和响应数据
相关链接:AJAX详解-廖雪峰官网