如何为jQuery UI自动完成搜索的列表项添加可跳转的锚点链接
第一步:调整后端接口返回学生ID
你需要先让fetch_data.php返回每个学生的唯一ID,用来拼接详情页的跳转参数,修改后的fetch_data.php代码如下:
<?php include('dbcon.php'); if(isset($_GET["term"])) { // 注意:原代码存在SQL注入风险,建议改为预处理查询,此处先保留原有逻辑做功能调整 $term = $_GET["term"]; $result = $conn->query("SELECT * FROM student WHERE name LIKE '%".$term."%' ORDER BY name ASC"); $total_row = mysqli_num_rows($result); $output = array(); if($total_row > 0){ foreach($result as $row) { $temp_array = array(); $temp_array['value'] = $row['name']; $temp_array['id'] = $row['id']; // 新增返回学生ID字段 $temp_array['label'] = '<img src="images/'.$row['photo'].'" width="70" /> '.$row['name'].''; $output[] = $temp_array; } }else{ $output['value'] = ''; $output['label'] = 'No Record Found'; } echo json_encode($output); } ?>
第二步:调整前端自动完成的渲染和点击逻辑
你原有代码里_renderItem方法的标签写法有误,混淆了li和a标签,修改后的JS代码如下:
$(document).ready(function(){ $('#search_data').autocomplete({ source: "fetch_data.php", minLength: 1, select: function(event, ui) { // 如果选中项有学生ID,直接跳转到详情页 if(ui.item.id){ window.location.href = 'student.php?id=' + ui.item.id; } $('#search_data').val(ui.item.value); return false; // 不需要默认赋值行为可以去掉该行 } }).data('ui-autocomplete')._renderItem = function(ul, item){ // 正确结构:li内部包裹a标签,href拼好跳转地址 return $("<li></li>") .data("item.autocomplete", item) .append($("<a href='student.php?id="+ (item.id || 'javascript:void(0)') +"' class='ui-autocomplete-row'></a>").html(item.label)) .appendTo(ul); }; });
补充说明
- 你需要确认student表的主键字段名,如果不是
id,对应替换fetch_data.php里的$row['id']即可 - 原有SQL查询直接拼接用户输入参数,存在严重的SQL注入风险,强烈建议改成MySQLi预处理查询方式
- 如果需要详情页在新窗口打开,给a标签加上
target="_blank"属性即可
内容的提问来源于stack exchange,提问作者llea 123
相关产品推荐
相关产品推荐

