首页 > 解决方案 > ajax laravel 实时搜索问题

问题描述

public function search_inv(Request $request)
{
    if($request->ajax()) {
        $data = inventory::where('p_name', 'LIKE', $request->country.'%')->get();
        $output = '';
       
        if (count($data)>0) {
            $output = '<ul class="list-group" style="display: block; position: relative; z-index: 1">';
            foreach ($data as $row) {
                $output .= '<table class="table table-bordered table-hover" id="abc" style="width:100%; float:right;">
                <tr style="width:100%;">
                    <th style="width:17.5%; text-align:center;">Piece Name</th>
                    <th style="width:15%; text-align:center;">Piece Model</th>
                    <th style="width:14%; text-align:center;">Piece Quantity</th>
                    <th style="width:13%; text-align:center;">Piece Price</th>
                   
                </tr>';
                
              $output.="<tr><td style=text-align=center>$row->p_name</td><td style=text-align=center>$row->p_model</td><td style=text-align=center>$row->p_Pieces</td><td style=text-align=center>$row->p_amount</td></tr>";
            }
            $output .=   '</table>';
        } else {
            $output .= '<li class="list-group-item">'.'No results'.'</li>';
        }
        return $output;
    }
}

我不知道它搜索完美的问题是什么,但是当我删除搜索时,它会复制表头。

在此处输入图像描述

标签: ajaxlaravelsearchlive

解决方案


那是因为您的标题在您的 foreach 循环中,因此每次迭代时,它都会将标题附加到输出字符串(也是您的打开表元素)。

这应该可以解决您的问题:

 if($request->ajax()) {
      
    $data = inventory::where('p_name', 'LIKE', $request->country.'%')->get();
    
    $output = '<table class="table table-bordered table-hover" id="abc" style="width:100%; float:right;">';
    $output .= '<tr style="width:100%;">
                    <th style="width:17.5%; text-align:center;">Piece Name</th>
                    <th style="width:15%; text-align:center;">Piece Model</th>
                    <th style="width:14%; text-align:center;">Piece Quantity</th>
                    <th style="width:13%; text-align:center;">Piece Price</th>
                </tr>';

    if (! $data) {
        $output .= '<li class="list-group-item">No results</li>';
    }else{
        $data->each( function( $row ) use ( &$output ){
            $output .= '<tr>
                <td style="text-align:center">' . $row->p_name . '</td>
                <td style="text-align:center">' . $row->p_model . '</td>
                <td style="text-align:center">' . $row->p_Pieces . '</td>
                <td style="text-align:center">' . $row->p_amount . '</td>
            </tr>';
        });
    }

    $output .= '</table>';
    
    return $output;
}

推荐阅读