您好,欢迎来到品趣旅游知识分享网。
搜索
您的当前位置:首页jQuery+AJAX+PHP+MySQL开发搜索无跳转无刷新的功能

jQuery+AJAX+PHP+MySQL开发搜索无跳转无刷新的功能

来源:品趣旅游知识分享网

演示:

1、当表单无输入任何关键词的时候,返回"请输入关键词..."

2255025658-5b47bdb47_articlex[1].gif

2、当表单输入的关键词查询无果的时候,返回"无结果"

4138693906-5b47550a799_articlex[1].gif

3、当表单输入的关键词查询有结果,则返回结果。

1682155967-5b47556cc3397_articlex[1].gif

表单页面

index.html

<!DOCTYPE html>
<html>
<head> 
 <meta charset="utf-8">
 <meta http-equiv="X-UA-Compatible" content="IE=edge">
 <title>AJAX搜索</title>
 <style type="text/css">
 *{margin:0px;padding:0px;}
 h2{
 text-align: center;
 }

 #search_con{
 width: 300px;
 margin:10px auto;
 }

 #keywords{
 width: 300px;
 margin-top: 10px;
 height: 30px;
 }

 #btn{
 width: 305px;
 height: 35px;
 margin-top: 10px;
 }

 #search_result{
 width: 300px;
 margin:30px auto;
 }
 </style>
 <script src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
 <script>
 $(function(){
 $("button").click(function(){
 var inputVal = $("#keywords").val();
 $.ajax({
 type:"GET",
 url:"search.php?keywords=" + inputVal,
 dataType:"json",
 success:function(data){
 $(function(){
 var con="";
 $.each(data,function(i,data){
 if (data.result == "0") {
 con+="<p>请输入关键词...</p>"
 }else if(data.result == "1"){
 con+="<p>无结果</p>"
 }else{
 con+="<p>"+data.title+"</p>"
 }
 });
 console.log(con);
 $("#search_result").html(con);
 })
 return false; 
 }
 })
 })
 })
 </script>
</head>
<body>
<!-- 表单 -->
 <p id="search_con">
 <form action="##">
 <h2>AJAX+PHP+MySQL搜索</h2>
 <input type="text" name="keywords" id="keywords" placeholder="搜索关键词..."><br/>
 <button name="button" type="button" id="btn">搜索</button>
 </form>
 </p>
 <!-- 搜索结果显示区域 -->
 <p id="search_result"></p>
</body>
</html>

服务端

search.php

<?php
header("Content-type:application/json");
//定义参数
$keywords = $_GET["keywords"];
//获取数据库配置
require_once("config.php");
//连接数据库
$con = mysql_connect($host,$username,$password);
 if (!$con)
 {
 die('连接数据库失败,失败原因:' . mysql_error());
 }
 //设置数据库字符集 
 mysql_query("SET NAMES UTF8");
 //查询数据库
 mysql_select_db($db, $con);
 //过滤关键词左右空格
 $keyword = trim($keywords);
 if (empty($keyword)) {
 //如果关键词为空,则返回result=0
 echo "[{\"result\":\"0\"}]";
 }else{
 $result = mysql_query("SELECT * FROM $tb WHERE title like '%$keyword%' ORDER BY ID DESC");
 $num = mysql_num_rows($result);
 if ($num) {
 $search_result = array();
 while($row = mysql_fetch_array($result)){
 $search_result[] = $row;
 }
 // 将数组转成json格式
 echo json_encode($search_result);
 
 }else{
 //如果查询无果,则返回result=1
 echo "[{\"result\":\"1\"}]";
 }
}
?>

数据库配置

config.php

<?php
//配置文件 - BY TANKING
$host="localhost";
$username="root";
$password="root";
$db="test";
$tb="datalist";
?>

数据库结构

262472067-5b4753fa85e_articlex[1].png

数据库名:test
表名:datalist
字段:id,title,url
字段解析:
id - 自增ID
title - 标题
url - 页面链接

Copyright © 2019- pqdy.cn 版权所有 赣ICP备2024042791号-6

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务