vue中axios实现数据交互与跨域问题

2020-06-16 05:39:30易采站长站整理

el:"#app",
data:{
city:"",
},
methods:{
get_weather(){
// http://wthrcdn.etouch.cn/weather_mini?city=城市名称
axios.get("http://wthrcdn.etouch.cn/weather_mini?city="+this.city)
.then(response=>{
console.log(response);

}).catch(error=>{
console.log(error.response)
});
}
}
})
</script>
</body>
</html>

总结:

1. 发送ajax请求,要通过$.ajax(),参数是对象,里面有固定的参数名称。


$.ajax({
"url":"数据接口url地址",
"method":"http请求方式,前端只支持get和post",
"dataType":"设置服务器返回的数据格式,常用的json,html,jsonp,默认值就是json",
// 要发送给后端的数据参数,post时,数据必须写在data,get可以写在data,也可以跟在地址栏?号后面
"data":{
"数据名称":"数据值",
}
}).then(function(resp){ // ajax请求数据成功时会自动调用then方法的匿名函数
console.log( resp ); // 服务端返回的数据
}).fail(function(error){ // ajax请求数据失败时会自动调用fail方法的匿名函数
console.log( error );
});

2. ajax的使用往往配合事件/钩子操作进行调用。

jQuery还提供了$.get 和 $post简写$.ajax的操作。


// 发送get请求
// 参数1:数据接口的请求地址
// 参数2:发送给接口地址的数据参数
// 参数3:ajax请求成功以后,调用的匿名函数,匿名函数的第一个参数还是服务端返回的数据
// 参数4:设置服务端返回的数据格式,告诉给jQuery
$.get("test.php", { "func": "getNameAndTime" },
function(data){
alert(data.name); // John
console.log(data.time); // 2pm
}, "json");
// 发送post请求
// 参数1:数据接口的请求地址
// 参数2:发送给接口地址的数据参数
// 参数3:ajax请求成功以后,调用的匿名函数,匿名函数的第一个参数还是服务端返回的数据
// 参数4:设置服务端返回的数据格式,告诉给jQuery
$.post("test.php", { "func": "getNameAndTime" },
function(data){
alert(data.name); // John
console.log(data.time); // 2pm
}, "json");

1.2.4 同源策略

同源策略,是浏览器为了保护用户信息安全的一种安全机制。所谓的同源就是指代通信的两个地址(例如服务端接口地址与浏览器客户端页面地址)之间比较,是否协议、域名(IP)和端口相同。不同源的客户端脚本[javascript]在没有明确授权的情况下,没有权限读写对方信息。

ajax本质上还是javascript,是运行在浏览器中的脚本语言,所以会被受到浏览器的同源策略所限制。