欢迎来到代码驿站!

JavaScript代码

当前位置:首页 > 网页前端 > JavaScript代码

jq.ajax+php+mysql实现关键字模糊查询(示例讲解)

时间:2021-03-21 10:30:40|栏目:JavaScript代码|点击:

对于这个功能企业上还算比较实用,推荐给大家;

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<style>
*{margin:0;padding:0;}
.text{width:200px;height:30px;line-height:30px;font-size:14px;outline:none;}
ul{width:200px;height:auto;border:1px solid #999;border-top:none;}
ul li{width:200px;height:30px;line-height:30px;font-size:14px;}
li:hover{background:#ddd;}
</style>

<body>
<input type="text" class="text" name="text">
<ul class="sea"></ul>

<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript">

$(".text").bind("input", function() { 
	if($(this).val().length>0){
		search();
	}else{
		$(".sea").html('');

	}
})
function search(){
	$.ajax({
		type:"GET",
		url:"sea.php",
		data:{"text":$(".text").val()},
		success:function(response){
			//转换成json对象
			eval("var json="+response);
			//console.log(json)
				var str="";
				for(var i=0;i<json.length;i++){
				str += "<li>" + json[i].sea + "</li>";
				}

				$(".sea").html(str);
		}
	})
}
</script>
</body>
</html>

sea.php

<?php
$con = mysqli_connect("localhost","username","password");
if(!$con){
	echo "数据库链接失败";
	exit;
}
mysqli_select_db($con,'jwhuang');
mysqli_query($con,'set names utf-8');
$text= isset($_GET['text']) ? trim($_GET['text']) : '';
$result=mysqli_query($con,"select * from search where sea LIKE '{$text}%' ");
$search=array();

while($row=mysqli_fetch_assoc($result)){
	//判断是否有对应的数据
	if(!$row){
		$search='';
		exit;
	}else{
		//对查询关键字进行标记
		$row['sea'] = str_replace($text, '<font color="red">' .$text. '</font>', $row['sea']);
		$search[]=$row;
		
	}
}
echo json_encode($search);
?>

效果图

完整代码下载:https://github.com/jwhuang59/Demos/tree/master/search

上一篇:基于Ajax表单提交及后台处理简单的应用

栏    目:JavaScript代码

下一篇:一个可以显示当前年份以及生肖的js代码

本文标题:jq.ajax+php+mysql实现关键字模糊查询(示例讲解)

本文地址:http://www.codeinn.net/misctech/85235.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有