越来越少人用JQuery,但你就不学了吗?(5)

如需要跟多资料请点击下方图片⬇(扫码加好友→备注66)
image

Jquery Ajax

$.ajax

​ jquery调用ajax方法:

​ 格式:$.ajax({});

​ 参数:

​ type:请求方式GET/POST

​ url:请求地址url

​ async:是否异步,默认是true表示异步

​ data:发送到服务器的数据

​ dataType:预期服务器返回的数据类型

​ contentType:设置请求头

​ success:请求成功时调用此函数

​ error:请求失败时调用此函数

get请求

$.ajax({
	type:"get",
	url:"js/cuisine_area.json",
	async:true,
	success : function (msg) {
		var str = msg;
		console.log(str);
		$('div').append("<ul></ul>");
		for(var i=0; i<msg.prices.length;i++){
			$('ul').append("<li></li>");
				$('li').eq(i).text(msg.prices[i]);
		}
	},
	error : function (errMsg) {
		console.log(errMsg);
		$('div').html(errMsg.responseText);
	}
});

post请求

$.ajax({
	type:"post",
	data:"name=tom",
	url:"js/cuisine_area.json",
	contentType: "application/x-www-form-urlencoded",
	async:true,
	success : function (msg) {
		var str = msg;
		console.log(str);
		$('div').append("<ul></ul>");
		for(var i=0; i<msg.prices.length;i++){
			$('ul').append("<li></li>");
			$('li').eq(i).text(msg.prices[i]);
		}
	},
	error : function (errMsg) {
		console.log(errMsg);
		$('div').html(errMsg.responseText)
	}
});

$.get

​ 这是一个简单的 GET 请求功能以取代复杂 $.ajax 。

​ 请求成功时可调用回调函数。如果需要在出错时执行函数,请使用 $.ajax。

// 1.请求json文件,忽略返回值
$.get('js/cuisine_area.json');					
// 2.请求json文件,传递参数,忽略返回值
$.get('js/cuisine_area.json',{name:"tom",age:100});	
// 3.请求json文件,拿到返回值,请求成功后可拿到返回值
$.get('js/cuisine_area.json',function(data){
	console.log(data);
});	
// 4.请求json文件,传递参数,拿到返回值	
$.get('js/cuisine_area.json',{name:"tom",age:100},function(data){
	console.log(data);
});

$.post

​ 这是一个简单的 POST 请求功能以取代复杂 $.ajax 。

​ 请求成功时可调用回调函数。如果需要在出错时执行函数,请使用 $.ajax。

// 1.请求json文件,忽略返回值
$.post('../js/cuisine_area.json');					
// 2.请求json文件,传递参数,忽略返回值
$.post('js/cuisine_area.json',{name:"tom",age:100});
// 3.请求json文件,拿到返回值,请求成功后可拿到返回值
$.post('js/cuisine_area.json',function(data){
	console.log(data);
});					
// 4.请求json文件,传递参数,拿到返回值	
$.post('js/cuisine_area.json',{name:"tom",age:100},function(data){
	console.log(data);
});

$.getJSON

​ 表示请求返回的数据类型是JSON格式的ajax请求

$.getJSON('js/cuisine_area.json',{name:"tom",age:100},function(data){
	console.log(data); // 要求返回的数据格式是JSON格式
});
posted @ 2020-07-06 17:00  乐字节教育  阅读(93)  评论(0编辑  收藏  举报