其实axios和ajax都对原生的xhr进行了封装,个人感觉还是axios简洁、方便,尤大大都让我们转axios了,确实对于ajax好了不少,它支持了promise对象,支持js最新的规范。简单易用。
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.js"></script> <!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/core.js"></script> --><!-- vue --><script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script><!-- 推荐使用:axios HTTP Client 网络通信的函数库 --><script src="https://unpkg.com/axios/dist/axios.min.js"></script><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"crossorigin="anonymous"><title>Document</title> </head><body><div id="app"><table class="table"><thead><tr><th>学生姓名</th><th>学生电话</th><th>学生班级</th><th>操作</th></tr></thead><tbody><tr v-for="(v, index) in stu" :key="index"><td scope="row">{{v.vname}}</td><td>{{v.vphone}}</td><td>{{v.vclazz.mtitle}}</td><td><button type="button" @click="ajaxdelete(v.vid)" class="btn btn-danger">删除</button></td></tr></tbody></table></div> </body><script>new Vue({el: '#app',data: {stu: []},mounted() {axios.get("/allstu").then((r) => {console.log("data:", r.data)this.stu = r.data;});// $.ajax({// url:"/test",// type:'post',// contentType:"application/json; charset=utf-8",// data:JSON.stringify(1),// success:function(r){// console.log("测试实数",r);// console.log("ok");// }// });this.xhrtest();},methods: {ajaxdelete:function(id){console.log("id",id);$.ajax({url:"/delete",type:"POST",contentType: "application/json; charset=utf-8",data:JSON.stringify(id),succcess:()=>{alert("成功提交!")}})},xhrtest:function(){// 创建xhr对象 let xhr ;if(window.XMLHttpRequest){xhr = new XMLHttpRequest();}else{xhr = new ActiveXObject('Microsoft.XMLHTTP');}//发送请求//如果修改第三个参数为true,你会发现,之后的xhr成功返回数据,但是status不会执行if语句,也就是说,你看不到“这个成功了”的输出//如果改为false,google浏览器会提示你这个同步的xmlHttpRequest已经过时了,因为它影响了用户体验// Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.xhr.open("POST","/test",true);xhr.setRequestHeader('Content-Type', ' application/json');//发送请求数据xhr.send(JSON.stringify(1));// if((xhr.status >= 200 && xhr.status< 300)|| xhr.status == 304){// alert(xhr.responseText);// console.log("这个成功了了!")// }else{// alert('request was unsuccessful:'+xhr.status);// console.log("状态码:",xhr.status);// console.log("xhr测试失败!");// }// 返回的响应有:// responseText:作为响应主体被返回的文本// responseXML:XML文档// status , statusText:状态码说明//如果为true,表示异步通信,应该改为如下方式xhr.onreadystatechange =function(){if(xhr.readyState == 4){if((xhr.status >= 200&& xhr.status<300)||xhr.status ==304){alert(xhr.responseText);console.log("ok");}else{alert("Request was unsuccessful:"+xhr.status);}}}}}}); </script></html>