一、发送ajax请求
1.简介
vue本身不支持发送ajax请求,需使用vue-resource、axios等插件来实现
axios时一个基于Promise的HTTP请求客户端,用来发送请求,也就是vue2.0官方推荐的,同时不再对vue-resource进行更新和维护
参考:GitHub上搜索axios,查看API文档
2.使用axios发送ajax请求
2.1 安装axios并引入
npm install axios -s
2.2 基本用法
// 普通请求方式
axios({
method:'get',
url:'user.json'
}).then(function(resp){
console.log(resp.data)
}).catch(function(resp){
console.log('请求失败:'+resp)
})
//get请求方式
写法:axios.get(url).then(function(response){}).catch(function(error){});
axios.get("http://localhost:9527/?name='yang'&age=27").then(function(resp){
console.log(resp.data); // 输出: /?name=%22yang%22&age=%2227%22
}).catch(function(error){
console.log(error)
})
// post请求方式
写法:axios.post(url,data).then(function(response){}).catch(function(error){});
axios.post("http://localhost:9527/",{
name:"yang",
age:27
}).then(function(response){
console.log(response);
}).catch(function(error){
console.log(error);
});
ps:axios默认发送数据时,数据格式时Request Payload,并不是我们常用的From Data格式,所以参数必须要以键值对形式传递,不能以json形式传参
1).自己拼接为键值对
axios.post("http://localhost:9527/","name=yang&age=27").then(function(response){
console.log(response);
}).catch(function(error){
console.log(error);
});
2).使用transformRquest方法,在请求发送之前转换json格式为字符串传递数据
axios.post("http://localhost:9527/",{
name:"yang",
age:27
},{
transformRquest:[
function(data){
var jsonToString = "";
for(var i in data){
jsonToString+= i +"="+ data[i] + "&";
}
return jsonToString;
}
]
}).then(function(response){
console.log(response);
}).catch(function(error){
console.log(error);
})
-------------华丽的分割线--------------
小问题:
.then(function(response){"在这里里面赋值"}),用vue {{}} 渲染response返回的值,如果用es5函数的写法,{{}}内渲染不出来值,但是console.log可以打印有返回值。
解决办法:改为es6的箭头函数 {{}} 内就可以渲染出来最新的返回值(?)
.then(response => {"在这里里面赋值"})
-------------华丽的分割线--------------
3).如果使用模块话开发,可以使用qs,querystring
axios本身是不支持发送跨域请求的,没有提供相应的API,所以只能使用第三方库
------后台部分:node.js------
var http = require("http");
http.createServer(function(request, response){
response.setHeader("Access-Control-Allow-Origin","*"); // 允许跨域
var url = request.url; // 获取url
response.write(url);
response.end();
}).listen(9527);
3.使用vue-resource发送跨域请求
3.1 安装vue-resource并引入
npm install vue-resource -s
3.2 基本用法
this.$http.jsonp(url,{
params:{
wd:'a'
},
jsonp:'cb'
}).then(function(response){
}).catch(function(error){
})
4.练习:百度搜索列表
demo链接