Ajax异步请求(JavaScript,jQuery,Vue)

异步和同步
  • 同步:客户端必须等待服务器端的响应,在等待的期间客户端不能进行其他的操作。
  • 异步:客户端不需要等待服务器端的响应,在服务器处理请求的过程中,客户端可以进行其他的操作。

Ajax采用的就是异步请求。

Ajax概述

Ajax是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术,通过在后台与服务器进行少量数据交换,Ajax 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
传统的网页(不使用 Ajax)如果需要更新内容,必须重载整个网页页面。Ajax大大提升了用户的体验。

1.JavaScript实现

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
	</body>
	<script type="text/javascript">
		//1.创建请求对象 XMLHttpRequest对象
		var xmlhttp;
		if(window.XMLHttpRequest){//验证浏览器
			xmlhttp=new XMLHttpRequest();
		}
		//2.发送ajax请求 利用网上提供好的借口来模拟
		var url="http://wthrcdn.etouch.cn/weather_mini?city=西安";
		xmlhttp.open("GET",url,true);
		xmlhttp.send();
		//onreadystatechange事件 前台准备好接受后台相应的时间 当请求被发送到服务器时,我们需要执行一些基于响应的任务
		xmlhttp.onreadystatechange=function(){
			if(xmlhttp.readyState==4&&xmlhttp.status==200){
				//服务器响应    获得来自服务器的响应 使用XMLHttpRequest对象的responseText属性
				var jsonstr=xmlhttp.responseText;//后台响应的是JSON字符串
				var jsonobj=JSON.parse(jsonstr);
				alert(jsonobj.data.yesterday.type);
			}
		}
	</script>
</html>

2.jQuery实现

语法

语法:$.get(url,data,callback,type)
参数:
url:请求路径
data:请求参数
callback:回调函数
type:响应结果的类型

案例演示

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script src="js/jquery.1.js" type="text/javascript" charset="utf-8"></script>
	</head>
	<body>
		<button type="button" id="btn_get">发送get请求</button>
		<button type="button" id="btn_post">发送post请求</button>
	</body>
	<script type="text/javascript">
		$('#btn_get').click(function() {
			$.get("https://autumnfish.cn/api/joke/list", {
				"num": "1"
			}, function(resp) {
				alert(resp);
				alert(resp.msg);
			}, "json")
		})
		$('#btn_post').click(function(){
			$.post("http://localhost:8080/login",{
				"username":"zhangsan",
				"password":"123456"
			},function(resp){
				alert(resp);
				alert(resp.msg)
			},"json")
		})
	</script>
</html>

3.Vue实现

Vue中的Ajax异步请求是由引入特定的库来完成的

(1)引入vue-resource库实现
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
		<script src="https://cdn.staticfile.org/vue-resource/1.5.1/vue-resource.min.js"></script>
	</head>
	<body>
		<div id="box">
			<button type="button" @click="sendAjax()">发送Ajax请求</button>
		</div>
	</body>
	<script type="text/javascript">
		new Vue({
			el: '#box',
			data: {},
			methods: {
				sendAjax() {
					//这个借口后台没有进行跨域处理 所以前台要以jsonp来请求
					/* this.$http.get('https://tcc.taobao.com/cc/json/mobile_tel_segment.htm', {
						params: {
							tel: '13709279984'
						}
					}).then(function(res) {
						//请求成功
						alert(res.body)
					}, function(res) {
						//请求失败
						console.log(res.status)
					}) */
					//json请求
					var url='https://tcc.taobao.com/cc/json/mobile_tel_segment.htm';
					this.$http.jsonp(url,{
						params:{
							tel:'13709279984'
						},
						jsonp:'callback'
					}).then(function(res){
						alert(res.body.catName)
					},function(res){
						//请求失败
					})
				}
			}
		})
	</script>
</html>
(2)引入axios库来实现
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
		<script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>
	</head>
	<body>
		<div id="box">
			<button type="button" @click="sendAjax()">get方式发送Ajax请求</button>
			<button type="button" @click="sendAjax1()">post方式发送Ajax请求</button>
		</div>
	</body>
	<script type="text/javascript">
		new Vue({
			el: '#box',
			data: {

			},
			methods: {
				//axios这个库没有jsonp请求,它首选的跨域方案是crose跨域
				//https://autumnfish.cn/api/joke/list?num=1
				sendAjax() {
					axios.get('https://autumnfish.cn/api/joke/list', {
						params: {
							num: 1
						}
					}).then(function(res) {
						alert(res.data.msg)
					}).catch(function(error) {
						console.log(error)
					})
				},
				/* axios.post('/user', {
				    firstName: 'Fred',        // 参数 firstName
				    lastName: 'Flintstone'    // 参数 lastName
				  })
				  .then(function (response) {
				    console.log(response);
				  })
				  .catch(function (error) {
				    console.log(error);
				  }); */
			}
		})
	</script>
</html>
发布了58 篇原创文章 · 获赞 13 · 访问量 1856

猜你喜欢

转载自blog.csdn.net/weixin_44324174/article/details/105129671