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>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章