Ajax-jq中Ajax的使用、todo案例(ajax增删改查)

Jq中的Ajax

$.ajax()的使用
方法的概述:

  • 作用1: 发送Ajax请求。

				$.ajax({
				// 请求方式
				type: 'post',
				// 请求地址
				url: '/user',
				// 在请求发送之前调用
				beforeSend: function () {
					alert('请求不会被发送')
					// 请求不会被发送
					return false;
				},
				// 请求成功以后函数被调用
				success: function (response) {
					// response为服务器端返回的数据
					// 方法内部会自动将json字符串转换为json对象
					console.log(response);
				}
			})

作用2: 发送jsonp请求。


	function fn (response) {
			console.log(response)
		}

		$('#btn').on('click', function () {
			$.ajax({
				url: '/jsonp',
				//要发送jsonp请求
				dataType: 'jsonp',
				//向服务端传递函数名字的参数名称
				jsonp: 'cb',
				jsonpCallback:'fn'//指定函数名称自己创建的
				// success: function (response) {
				// 	console.log(response);

				// }
			})
		});
serialize()方法
作用:将表单中的数据自动拼接成字符串类型的参数
var params = $('#form').serialize();// name=zhangsan&age=30

//第一个参数、请求路径、第二个参数、请求参数、第三个参数:回调函数
$.get
作用: 用于发送get请求
$.get('http://www.example.com', {name: 'zhangsan', age: 30}, function (response) {}) 

$.post
作用: 用于发送post请求
$.post('http://www.example.com', {name: 'lisi', age: 22}, function (response) {})



全局事件()
只要页面中有Ajax请求被发送,对应的全局事件就会被触发
.ajaxStart()     // 当请求开始发送时触发
.ajaxComplete()  // 当请求完成时触发

nprogress 进度条插件

<link rel='stylesheet' href='nprogress.css'/>
<script src='nprogress.js'></script>


NProgress.start();  // 进度条开始运动 
NProgress.done();   // 进度条结束运动

RESTful 风格的API
主要是一套接口的规范

方法作用
get获取数据
post添加数据
put更新数据
delete删除数据

传统的表单是不支持提交的、ajax中是支持的
RESTful风格的特点:请求地址相同、请求方式不同
例子

//服务端路由
// 修改某一个用户的信息
app.put('/users/:id',function (req,res) {
	const id= req.params.id;
	res.send(`这是修改用户信息${id}的路由`);
  })
  
  //客户端请求
  	// 修改id为1的用户信息
		$.ajax({
			type:'put', 
			url:'/users/10',
			success:function(response){
				console.log(response);
				
			}
		})

todo案例

<body>
	<section class="todoapp">
		<!-- 添加 -->
		<header class="header">
			<h1>todos</h1>
			<input type="text" class="new-todo" placeholder="What needs to be done?" autofocus id="task">
		</header>
		<!-- This section should be hidden by default and shown when there are todos -->
		<section class="main">
			<input class="toggle-all" type="checkbox">
			<!-- 页面展示模块 -->
			<ul class="todo-list" id="todo-list">

			</ul>
		</section>
		<!-- This footer should hidden by default and shown when there are todos -->
		<footer class="footer">
			<!-- This should be `0 items left` by default -->
			<span class="todo-count"><strong id="count">0</strong> item left</span>
			<!-- Remove this if you don't implement routing -->
			<ul class="filters">
				<li>
					<a class="selected" href="javascript:;">All</a>
				</li>
				<li>
					<a href="javascript:;">Active</a>
				</li>
				<li>
					<a href="javascript:;">Completed</a>
				</li>
			</ul>
			<!-- 如果没有已完成的项目,则隐藏↓ -->
			<button class="clear-completed">Clear completed</button>
		</footer>
	</section>
	<script src="/js/jquery.min.js"></script>
	<script src="/js/template-web.js"></script>
	<script src="/js/nprogress/nprogress.js"></script>

	<!-- 添加模板 -->
	<script type="text/html" id="taskTpl">
		{{each tasks}}
	<li class="{{$value.completed?'completed':''}}">
		 <div class="view">
			  <input class="toggle" type="checkbox" {{$value.completed?'checked':''}}/>
			  <label>{{$value.title}}</label>
			  <button class="destroy" data-id="{{$value._id}}"></button>
		 </div>
		 <input class="edit">
	</li>
	{{/each}}
</script>

	<script type="text/javascript">
		//用于列表展示
		//用于存放任务列表中的数组
		var taskAry = [];

		//当页面有ajax请求时触发
		$(document).on('ajaxStart',function () {
			NProgress.start();
			
		  })
	   //当页面ajax请求完成时触发
	   $(document).on('ajaxComplete',function () {
		NProgress.done()
			
		  })
		//向服务器端发送请求、获取已经存在的任务
		$.ajax({
			url: '/todo/task',
			type: 'get',
			success: response => {
				//将已存在的任务储存在变量中
				taskAry = response
				//模板方法
				render();
				//计算未完成任务数量
				calcCount();
			}
		})
		//添加任务
		//获取文本框添加键盘抬起事件
		$('#task').on('keyup', function (event) {
			//如果用户敲击了回车键
			if (event.keyCode == 13) {
				//判断用户是否输入了用户名称
				var taskName = $(this).val();
				//如果输入为空
				if (taskName.trim().length == 0) {
					alert('你还没有输入内容呢');
					//阻止执行
					return;
				}
				//先服务端发送请求、添加任务
				$.ajax({
					type: 'post',
					url: '/todo/addTask',
					contentType: 'application/json',
					data: JSON.stringify({ title: taskName }),
					success: (response) => {
						//将输入框的值追加到任务列表中
						taskAry.push(response);
						//模板方法
						render()
						//清空文本框的值
						$('#task').val('')
						//计算未完成任务数量
						calcCount();
					}
				})

			}

		})
		//拼接字符串、将拼接好的字符串显示在页面中
		function render() {
			//拼接模板
			var html = template('taskTpl', { tasks: taskAry });
			//渲染页面
			$('#todo-list').html(html)
		}

		//删除任务
		//事件委托
		//任务列表页面
		//点击删除触发事件
		$('#todo-list').on('click', '.destroy', function () {
			//获取id号
			var id = $(this).attr('data-id');
			console.log(id);

			$.ajax({
				url: '/todo/deleteTask',
				type: 'get',
				data: {
					_id: id
				},
				success: (response) => {
					//移除
					//item会对数组进行遍历、item指当前被遍历的id
					//设置查找条件:当前的id=被移除的id、会返回这个id在数组中的索引号
					var index = taskAry.findIndex(item => item._id == id);
					// console.log(index);
					//移除在数组中对应的索引号
					taskAry.splice(index, 1);
					//重新显示页面
					render();
					//计算未完成任务数量
					calcCount();

				}
			})
		})
		 
		//改变任务状态
		//用户改变用户改变任务名称前面的复选框时触发
		$('#todo-list').on('change', '.toggle', function () {
			//获取当前选中的状态、true选中、 false未选中
			const status = $(this).is(':checked');
			//console.log(status);
			//获取当前任务的id
			const id = $(this).siblings('button').attr('data-id');
			//console.log(id);

			//发送请求更改状态
			$.ajax({
				type: 'post',
				url: '/todo/modifyTask',
				//json字符串的方式传递当前数据更新数据库中的状态
				data: JSON.stringify({ _id: id, completed: status }),
				contentType: 'application/json',
				success: function (response) {
					//response服务端返回更新后的数据
					console.log(response);
					//根据返回的id获取数组中对应的数据

					var task = taskAry.find(item => item._id == id);
					//更改数组中id号对应的状态值
					task.completed = response.completed;
					//渲染更新好的页面
					render();
					//计算未完成任务数量
					calcCount();



				}
			})

		});

         //修改任务名称
		//双击事件修改标签中的值
		$('#todo-list').on('dblclick', 'label', function () {
			//双击后给li添加文本框
			$(this).parent().parent().addClass('editing');
			//获取当前的值给edit文本框并且获取焦点
			$(this).parent().next().val($(this).text()).focus();

		});
		//当文本框离开焦点时
		$('#todo-list').on('blur', '.edit', function () {
			//获取当前的任务名称
			var newTaskName = $(this).val();
			//获取id
			var id = $(this).siblings().find('button').attr('data-id');

			// 向服务器发送ajax请求、修改(更新)任务的名称
			$.ajax({
				url: '/todo/modifyTask',
				type: 'post',
				// json字符串
				contentType: 'application/json',
				data: JSON.stringify({ _id: id, title: newTaskName }),
				success: function (response) {
					//console.log(response);
					//将最新状态同步到数组中
					//find返回数组中这个对象
					var task = taskAry.find(item => item._id == id);
					console.log(task);

					//更新数组中的任务名称
					task.title = response.title;
					//更新页面
					render();
					//计算未完成任务数量
					calcCount();

				}
			})

		})


		//计算未完成用户的数量
		function calcCount() {
			//储存结果的变量
			var count = 0;
			//查找item.completed为false的数组元素
			//filter返回一个新的数组
			var newAry = taskAry.filter(item => item.completed == false)
			//count接收新数组(false)的长度
			count = newAry.length;

			//#count用于获取未完成数量放到string标签中
			//未完成的任务数量显示在页面中
			$('#count').text(count);
		}
	</script>

</body>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值