AJAX&&Axios
AJAX = Asynchronous JavaScript and XML(异步的 JavaScript 和 XML)。
<head> <script> function loadXMLDoc() { .... AJAX 脚本执行 ... } </script> </head>
步骤:
//1. 创建核心对象 var xhttp; if (window.XMLHttpRequest) { xhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xhttp = new ActiveXObject("Microsoft.XMLHTTP"); } //2. 发送请求 xhttp.open("GET", "http://localhost:8080/ajax-demo/ajaxServlet"); xhttp.send(); //3. 获取响应 xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { alert(this.responseText); } };
Axios
发送异步请求携带参数,在使用之前需要声明需要导入的js文件
<script src="js/axios-0.18.0.js"></script>
使用步骤:
<script> //1. get /* axios({ method:"get", url:"http://localhost:8080/ajax-demo/axiosServlet?username=zhangsan" }).then(function (resp) { alert(resp.data); })*/ //2. post axios({ method:"post", url:"http://localhost:8080/ajax-demo/axiosServlet", data:"username=zhangsan" }).then(function (resp) { alert(resp.data); }) </script>
或者使用别名的方式:
axios.get("http://localhost:8080/ajax-demo/axiosServlet?username=zhangsan").then(function (resp) { alert(resp.data); }) axios.post("http://localhost:8080/ajax-demo/axiosServlet","username=zhangsan").then(function (resp) { alert(resp.data); })
axios 是一个很强大的工具。我们只需要将需要提交的参数封装成 js 对象,并将该 js 对象作为 axios 的 data 属性值
进行,它会自动将 js 对象转换为 JSON 串进行提交。
js 提供的 JSON 对象我们只需要了解一下即可。因为 axios 会自动对 js 对象和 JSON 串进行想换转换。
发送异步请求时,如果请求参数是 JSON 格式,那请求方式必须是 POST 。因为 JSON 串需要放在请求体中。