1.异步查询数据,自然是通过ajax查询,大家首先想起的肯定是jQuery。但jQuery与MVVM的思想不吻合,而且ajax只是jQuery的一小部分。因此不可能为了发起ajax请求而去引用这么大的一个库。
2.vue.js的Ajax请求
1>安装axios
cnpm install axios --save
2>在main.js添加
import Axios from 'axios' Vue.prototype.$axios = Axios; new Vue({ el: '#app', Axios, components: { App }, template: '<App/>' })
3>一个基础的get请求方式
axios.get("/item/category/list?pid=0") // 请求路径和请求参数拼接 .then(function(resp){ // 成功回调函数 }) .catch(function(){ // 失败回调函数 }) // 参数较多时,可以通过params来传递参数 axios.get("/item/category/list", { params:{ pid:0 } }) .then(function(resp){})// 成功时的回调 .catch(function(error){})// 失败时的回调
4> 一个基础的post请求方式
axios.post("/user",{ name:"Jack", age:21 }) .then(function(resp){})// 成功时的回调 .catch(function(error){})// 失败时的回调
注意,POST请求传参,不需要像GET请求那样定义一个对象,在对象的params参数中传参。post()方法的第二个参数对象,就是将来要传递的参数
3Juqery的Ajax请求
<script type="text/javascript" src="../jquery/jquery-2.2.3.js"></script> <script type="text/javascript">$.ajax({ type: "POST", url: "some.php", data: "name=John&age=25", success: function(data){ alert(data.name); }, "json" }); </script>
参数
type:ajax的请求方式
url:发送请求地址
data:待发送Key/value值
callback:发送成功时回调函数
json:返回内容格式 xml html script json text _default
3.1>简写方式
$.post("test.php", //ajax的请求方式 { "name": "John" ,"age":25}, //请求参数 function(data){ //回调函数 alert(data.name); console.log(data.age); }, "json"); //返回数据的格式