欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

vue、jQuery的Ajax写法

程序员文章站 2022-07-15 14:31:34
...

VUE

vue本身不支持发送AJAX请求,需要使用vue-resource、axios等插件实现 axios是一个基于Promise的HTTP请求客户端,用来发送请求,也是vue2.0官方推荐的,同时不再对vue-resource进行更新和维护

axios(不支持发送跨域的请求)
  • axios([options])
send() {
		axios({
			method: 'get', //只能用get
			url: 'user1.json',
			}).then(res => { //参数可以重复
			console.log(res.data);
			}).catch(res => {
				console.log(res);
			})
		},
  • axios.get(url[,options]);
    传参方式:
    1.通过url传参
    2.通过params选项传参
Getsend() {
			axios.get('server.php', {
				params: {
					name: 'tom',
					age: '24',
				}
			}).then(re => {
				console.log(re.data);
			}).catch(re => {
				console.log("失败");
			})
		}
  • axios.post(url,data,[options]);
var vm = new Vue({
	el: '#c',
	methods: {
		Postsend() {
			axios.post('server.php', 'name=tom&age=20')//方法1,数据是死的
				.then(res => {
					console.log(res.data);
				}).catch(res => {
					console.log("错误");
				})
		}
	}
	});
Postsend() {
axios.post('server.php', this.user, { //需要this.user
	transformRequest: [function(data, headers) {
		let params = '';
	    for (let index in data) {
			params += index + '=' + data[index] + '&';
		}
		return params;
	}]
			}).then(resp => {
	console.log(resp.data);
}).catch(err => {
	console.log('请求失败:' + err.status + ',' + err.statusText);
	});
}

axios默认发送数据时,数据格式是Request Payload,并非我们常用的Form Data格式,所以参数必须要以键值对形式传递,不能以json形式传参
传参方式:
1.自己拼接为键值对
2.使用transformRequest,在请求发送前将请求数据进行转换
3.如果使用模块化开发,可以使用qs模块进行转换

vue-resource(支持发送跨域的请求)

使用this.$http发送请求

  • this.$http.get(url, [options])
  • this.$http.jsonp(url, [options])
  • this.$http.post(url, [body], [options])
//360浏览器
sendJ(){
	this.$http.jsonp('https://sug.so.360.cn/suggest',{
		params:{
			word:'a'
		},
	}).then(res=>{
		console.log(res.data.s)
	})
},
sendJB(){
	this.$http.jsonp('https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web&sugsid=1465,21106,29074,29522,29518,29721,29568,29220',{
		params:{
			wd:'a'
		},
		jsonp:'cb',
	}).then(res=>{
		console.log(res.data);
	})
}

jQuery

jQuery load() 方法是简单但强大的 AJAX 方法。
load() 方法从服务器加载数据,并把返回的数据放入被选元素中。

$(selector).load(URL,data,callback);

HTTP GET 请求从服务器上请求数据。
可选的 callback 参数是请求成功后所执行的函数名。

$.get(URL,callback);

HTTP POST 请求向服务器提交数据。

$.post(URL,data,callback);
相关标签: VUE jQuery Ajax