使用ajax搜索,在数组

时间:2017-04-27 16:25:59

标签: php jquery ajax laravel search

请帮助搜索脚本

$("#search").on("keyup",function(){
    var search=$("#search").val();
    search=search.replace(/  +/g, ' ');
    if(search.length>=1){
        var result=search.split("");
        $.ajax({  
            type: 'POST',  
            url: "{{URL('/searchajax')}}", 
            data: 
                { 
                    search:result
                },
            success: function(data) {
                $("#searchresult").css("display","block");
                if(data.length>0){
                    for(var i=0;i<data.length;i++){
                        $.each(data[i], function( index, value ) {
                            $("#itemssearch").append("<a href='{{URL('/product')}}/"+value.id+"'>\
                                                            <li>"+value.originalname+value.name+"</li>\n\
                                                        </a>\n\
                                                        ");

                            });
                    }
                }else{
                      ...
                }
            }
        });
    }
});

public function searchajax(Request $request){
    $search=$request->search;
        $return=DB::table("products")
                ->where('originalname', 'like', '%'.$search.'%')
                ->orWhere('name', 'like', '%'.$search.'%')
                ->orderby("products.table_id")
                ->take(5)
                ->get();

    return response()->json($return);
}
  1. 如果有搜索词“iphone 7s”如何首先搜索“iphone”然后“7s”并获得所有结果的一个变量
  2. 如果有搜索词“iphone 7s”如何首先搜索“iphone”然后 “7s”并将所有结果都变为一个变量

3 个答案:

答案 0 :(得分:3)

如果我理解正确,您希望orWhere()对每个单词应用foreach对:

$words = explode(' ', $search);

$result = Product::query();

foreach ($words as $word) {
    $result = $result->orWhere('originalname', 'like', '%'.$word.'%')
                     ->orWhere('name', 'like', '%'.$word.'%');
}

$result = $result->orderby("products.table_id")->take(5)->get();

答案 1 :(得分:0)

CodeIgniter的示例 控制器

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends CI_Controller {

    /**
     * Index Page for this controller.
     *
     * Maps to the following URL
     *      http://example.com/index.php/welcome
     *  - or -
     *      http://example.com/index.php/welcome/index
     *  - or -
     * Since this controller is set as the default controller in
     * config/routes.php, it's displayed at http://example.com/
     *
     * So any other public methods not prefixed with an underscore will
     * map to /index.php/welcome/<method_name>
     * @see https://codeigniter.com/user_guide/general/urls.html
     */
    public function index()
    {
        $this->load->model('common_model');
        $var1='engineering';

        $where=" id !='0'";
        $a['reco']=$this->common_model->get_entry_by_data('collages',false,$where);

        $this->load->view('welcome_message',$a);


    }


    public function ajaxcall()
    {   
    $searchval=$this->input->post('lalla');
    $this->load->model('common_model');

        $where="`city` like '%".$searchval."%' or `deparment` like '%".$searchval."%'";
        $a=$this->common_model->get_entry_by_data('collages',false,$where);


        $result='';
        $result="<table>
        <tr><td>name</td><td>city</td><td>deparment</td></tr>";
        if(!empty($a))
        { 
         foreach($a as $recos){
        $result.="<tr><td>". $recos['name']."</td><td>". $recos['city']."</td><td>". $recos['deparment']."</td></tr>"; 
        }
        }else{
            $result.="<tr><td>no result</td><td>no result</td><td>no result</td></tr>";

        }
        $result.="</table>";

        echo $result;



}
}

查看示例

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Welcome to CodeIgniter</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <style type="text/css">

    ::selection { background-color: #E13300; color: white; }
    ::-moz-selection { background-color: #E13300; color: white; }

    body {
        background-color: #fff;
        margin: 40px;
        font: 13px/20px normal Helvetica, Arial, sans-serif;
        color: #4F5155;
    }

    a {
        color: #003399;
        background-color: transparent;
        font-weight: normal;
    }

    h1 {
        color: #444;
        background-color: transparent;
        border-bottom: 1px solid #D0D0D0;
        font-size: 19px;
        font-weight: normal;
        margin: 0 0 14px 0;
        padding: 14px 15px 10px 15px;
    }

    code {
        font-family: Consolas, Monaco, Courier New, Courier, monospace;
        font-size: 12px;
        background-color: #f9f9f9;
        border: 1px solid #D0D0D0;
        color: #002166;
        display: block;
        margin: 14px 0 14px 0;
        padding: 12px 10px 12px 10px;
    }

    #body {
        margin: 0 15px 0 15px;
    }

    p.footer {
        text-align: right;
        font-size: 11px;
        border-top: 1px solid #D0D0D0;
        line-height: 32px;
        padding: 0 10px 0 10px;
        margin: 20px 0 0 0;
    }

    #container {
        margin: 10px;
        border: 1px solid #D0D0D0;
        box-shadow: 0 0 8px #D0D0D0;
    }
    </style>
</head>
<body>

<div id="container">
    <h1>Welcome to CodeIgniter!</h1>

    <div id="body">

        <input type="text" name="searchbox" value="" id="searchbox"/>
        <button name="btn" id="btn">search</button>
        <div id="replace">
        <table>
        <tr><td>name</td><td>city</td><td>deparment</td></tr>
        <?php foreach($reco as $recos){?>
        <tr><td><?php echo $recos['name'];?></td><td><?php echo $recos['city'];?></td><td><?php echo $recos['deparment'];?></td></tr>
        <?php }?>
        </table>
        </div>
</div>

</body>
</html>
<script>
$("#btn").click(function() {
    var searchval=$("#searchbox").val();

 $.ajax({
        url: "index.php/Welcome/ajaxcall", 
        type: "post",
        data: {'lalla':searchval} ,
        success: function (response) {
                   $("#replace").html(response);

        },



    });
    });
</script>

答案 2 :(得分:-1)

使用此自动填充功能,我在laravel 5.4中使用此代码

$('#search').on('input', function(){
    var search = $('#search').val(); //search input var

    if(search.length == 0){
        //do something if value of search box is empty
    } else {
        $('#search').autocomplete({
            source: function(request, response){
                $.ajax({
                    url: 'search', //route
                    data: { search:search },
                    dataType: 'json',
                    type: 'post',
                    success: function(data){
                        //here is your data
                    },
                    error: function(){
                        alert('Could not load the data');
                    }
                });
            }
        });
    }
});