1. 程式人生 > >js實現模糊搜尋

js實現模糊搜尋

功能一:關鍵字搜尋

總結:1、搜尋出的結果,前臺先要清空原有表格 $("#tbody").empty;

           2、後臺返回的json格式字串 js eval 專成物件var stus = eval("(" + msg + ")");,在迴圈進行字串拼接到表格上  $("#tbody").html(str);

$("#btn").click(function() {
			var id = $.trim($("#id").val());
			var classname = $.trim($("#classname").val());
			var clazz = $.trim($("#class").val());
			if (id == "" & classname == "" & clazz == "") {
				alert("請至少輸入一個篩選條件");
			} else {
				$.ajax({
					type : "post",
					url : "SearchServlet",
					data : {
						"type" : "find",
						"id" : id,
						"classname" : classname,
						"class" : clazz
					},
					success : function(msg) {
						if ("無結果" == msg) {
							alert(msg);
							$("#id").val("");
							$("#classname").val("");
							$("#class").val("");
						}
						var stus = eval("(" + msg + ")");
						$("#tbody").empty;
						var str = "";
						for (var i = 0; i < stus.length; i++) {
							str = str + "<tr><td>" + stus[i].id + "</td>"
							str = str + "<td>" + stus[i].studentNo + "</td>"
							str = str + "<td>" + stus[i].studentName + "</td>"
							str = str + "<td>" + stus[i].studentClass + "</td>"
							str = str + "<td>" + "<a href='javascript:a(" + stus[i].id + ")'>" + "刪除" + "</a>" + "</td></tr>"
						}
						$("#tbody").html(str);
					}
				}
				);
			}
		});
功能二:input框刪除關鍵字,動態顯示所有結果

總結:1、a標籤動態傳參,傳給後臺進行刪除,使用字串拼接str = str + "<td>" + "<a href='javascript:a(" + stus[i].id + ")'>" + "刪除" + "</a>" + "</td></tr>"

$(".input").on('input', function(e) {
			var id = $.trim($("#id").val());
			var classname = $.trim($("#classname").val());
			var clazz = $.trim($("#class").val());
			if (id == "" && classname == "" && clazz == "") {
				$.ajax({
					type : "post",
					url : "SearchServlet",
					data : {
						"type" : "all",
					},
					success : function(msg) {
						var stus = eval("(" + msg + ")");
						$("#tbody").empty;
						var str = "";
						for (var i = 0; i < stus.length; i++) {
							str = str + "<tr><td>" + stus[i].id + "</td>"
							str = str + "<td>" + stus[i].studentNo + "</td>"
							str = str + "<td>" + stus[i].studentName + "</td>"
							str = str + "<td>" + stus[i].studentClass + "</td>"
							str = str + "<td>" + "<a href='javascript:a(" + stus[i].id + ")'>" + "刪除" + "</a>" + "</td></tr>"
						}
						$("#tbody").html(str);
					}
				}
				);
			}
		});


功能三:刪除 table中的資料

總結:

       在a標籤裡面傳參 js寫在a標籤裡面的兩種方式

<td><ahref="javascript:a(${stu.id})">刪除</a></td>

<td><a href="javascript:void(0);" onclick="remove(${stu.id })">刪除</a></td>



function a(id) {
		$.ajax({
			type : "get",
			url : "SearchServlet?type=delete&id=" + id,
			success : function(msg) {
				alert(msg);
				if ("刪除成功" == msg) {
					$("tr").remove("#stu_" + id);
				}
			}
		});
	}