是否可以使用jQuery过滤已经获取的数据

6 javascript jquery laravel laravel-5

我正在使用Laravel框架并获取数据.现在我试图用Ajax和jQuery过滤数据.但是我面临的一个问题......

更新4

当我开始过滤时,会出现此错误循环:

"/var/www/html/laravel/vendor/laravel/framework/src/Illuminate/Routing/RouteCollection.php","line":255,"trace":[{"file":"/ var/www/html /laravel/vendor/laravel/framework/src/Illuminate/Routing/RouteCollection.php","line":242,"function":"methodNotAllowed","class":"Illuminate\Routing\RouteCollection","type": " - >"},

在那里,我错过了控制器的一些东西?还是路由?谢谢你的帮助!

Laravel控制器:

public function search(Request $request)
{
  $q = $request->q;
  $sortbyprice = $request->sortbyprice;
  $region = $request->region;
  $rooms = $request->rooms;
  $price = $request->price;
  $max = $request->input('max');
  $min = $request->input('min');

  $paginationData = [
      'q' => $q
  ];

  $estates = \DB::table('allestates')
      ->where('lat', '!=', '')
      ->where('lng', '!=', '')
      ->where('price', '!=', '')
      ->when($q, function($query, $q) use ($paginationData) {
          $paginationData['q'] = $q;
          return $query->where(function($query) use ($q) {
                      $query->where("building_name", "LIKE", "%" . $q . "%")
                          ->orWhere("address", "LIKE", "%" . $q . "%")
                          ->orWhere("company_name", "LIKE", "%" . $q . "%")
                          ->orWhere("region", "LIKE", "%" . $q . "%")
                          ->orWhere("rooms", "LIKE", "%" . $q . "%");
                  });
      })
      ->when($sortbyprice, function($query, $order) use ($paginationData) {
          if(!in_array($order, ['asc','desc'])) {
              $order = 'asc';
          }
          $paginationData['sortbyprice'] = $order;
          return $query->orderBy('price', $order);

      }, function($query) {
          return $query->orderBy('price');
      })
      ->when($region, function($query, $regionId) use ($paginationData) {
          $paginationData['region'] = $regionId;
          return $query->where('region', $regionId);
      })
      ->when($rooms, function($query, $roomsId) use ($paginationData) {
          $paginationData['rooms'] = $roomsId;
          return $query->where('rooms', "LIKE", "%" . $roomsId . "%");
      })
      ->when($max, function($query, $max) use ($min, $paginationData) {
          $paginationData['min'] = $min;
          $paginationData['max'] = $max;
          return $query->whereBetween('price', [$min, $max]);
      })
      // ->toSql()
      ->paginate(100);

  $paginationData = array_filter($paginationData);

  return view("home", compact('estates', 'q','paginationData'));
}
Run Code Online (Sandbox Code Playgroud)

var displayList = $('#display-wrapper ol');
var selectedOptions = {
    sortbyprice: '',
    rooms: '',
    region: ''
};


$('html').click(function () {
    console.log(selectedOptions);
});

$('a.region').on('click', function () {

    var selectValue = $(this).data('value');

    $('#region').text(selectValue);
    selectedOptions.region = selectValue;
    fetchDataFromServer(selectedOptions);
});

$('a.rooms').on('click', function () {
    var selectValue = $(this).data('value');

    $('#rooms').text(selectValue);
    selectedOptions.rooms = selectValue;
    fetchDataFromServer(selectedOptions);
});

$('a.sortbyprice').on('click', function () {
    var selectValue = $(this).text();

    selectedOptions.sortbyprice = selectValue;
    fetchDataFromServer(selectedOptions);
});

function serialize(options) {
    var arr = [];

    for (var key in options) {
        arr.push(key + '=' + options[key]);
    }

    return encodeURI(arr.join('&'));
}

function fetchDataFromServer(options) {
    $.ajax({
        type: 'POST',
        url: '/home',
        data: serialize(options),
        success: function (response) {
            if (response.error) {
                console.error(response.error);
            } else {
                console.log(response);
               
                updateDisplay(displayList);
            }
        },
        error: function (html, status) {
            console.log(html.responseText);
            console.log(status);
        }
    });
}

function updateDisplay(node, data) {
    var template = data.reduce(function (acc, item) {
        return acc + '<li><p>Region: ' + item.region + '</p><p>Price: ' + item.price + '</p><p>Rooms: ' + item.rooms + '</p></li>';
    }, '');

    node.empty();
    node.append(template);
}
Run Code Online (Sandbox Code Playgroud)
#filter-wrapper {
    margin-top: 15px
}

#filter-wrapper ul {
    list-style: none;
    position: relative;
    float: left;
    margin: 0;
    padding: 0
}

#filter-wrapper ul a {
    display: block;
    color: #333;
    text-decoration: none;
    font-weight: 700;
    font-size: 12px;
    line-height: 32px;
    padding: 0 15px;
    font-family: "HelveticaNeue", "Helvetica Neue", Helvetica, Arial, sans-serif
}

#filter-wrapper ul li {
    position: relative;
    float: left;
    margin: 0;
    padding: 0
}

#filter-wrapper ul li.current-menu-item {
    background: lightblue;
}

#filter-wrapper ul li:hover {
    background: #f6f6f6
}

#filter-wrapper ul ul {
    display: none;
    position: absolute;
    top: 100%;
    left: 0;
    background: #fff;
    padding: 0
}

#filter-wrapper ul ul li {
    float: none;
    width: 200px
}

#filter-wrapper ul ul a {
    line-height: 120%;
    padding: 10px 15px
}

#filter-wrapper ul ul ul {
    top: 0;
    left: 100%
}

#filter-wrapper ul li:hover>ul {
    display: block
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="filter-wrapper">
              <ul>
                  <li><a class="sortbyprice" href="javascript:" data-value="sortbyprice">Cheapest</a></li>
                  <li class="dropdown">
                      <a href="#" id="rooms">???</a>
                      <ul class="init" name="rooms">
                          <li><a class="rooms" href="javascript:" data-value="1DK">1DK</a></li>
                          <li><a class="rooms" href="javascript:" data-value="2LDK">2LDK</a></li>
                          <li><a class="rooms" href="javascript:" data-value="3LDK">3LDK</a></li>
                      </ul>
                  </li>

                  <li class="dropdown">
                      <a href="#" id="region">???</a>
                      <ul class="init" name="region">
                          <li><a class="region" href="javascript:" data-value="??">??</a></li>
                          <li><a class="region" href="javascript:" data-value="??">??</a></li>
                          <li><a class="region" href="javascript:" data-value="???">???</a></li>
                      </ul>
                  </li>
              </ul>
          </div>

          <div id="display-wrapper">
              <ol></ol>
          </div>
Run Code Online (Sandbox Code Playgroud)

Ray*_*han 1

主要思想是创建一个变量来存储用户选择的所有选项,并且在每个ajax请求上,将相应的数据发送到服务器以获得过滤结果。

\n\n

我删除了隐藏的 HTML 表单,并选择使用对象。

\n\n

此代码片段中的 ajax 请求不起作用,因为没有端点 \'/home\' 可供我获取资源,但我认为这将在您的计算机上工作。

\n\n

附带说明一下,id 属性应该是唯一的,否则,行为可能不是您所期望的。对于 onclick 处理程序,如果您有很多下拉菜单,您应该考虑使用循环生成它们,而不是像我一样复制和粘贴,但出于演示目的,我将暂时保留它。

\n\n

\r\n
\r\n
// a sample display\r\nvar displayList = $(\'#display-wrapper ol\');\r\n// create an object to store the selected options\r\nvar selectedOptions = {\r\n    sortbyprice: \'\',\r\n    rooms: \'\',\r\n    region: \'\'\r\n};\r\n\r\n// this event handler is for logging out the selectedOptions\r\n// so that you can see what happens to the variable\r\n// you should remove this in production\r\n$(\'html\').click(function () {\r\n    console.log(selectedOptions);\r\n});\r\n\r\n$(\'a.region\').on(\'click\', function () {\r\n    // I guess what you\'re trying to do here is to update the dropdown\r\n    // text into the selected value, e.g replace \xe3\x82\xa8\xe3\x83\xaa\xe3\x82\xa2 with \xe9\x96\xa2\xe8\xa5\xbf\r\n    var selectValue = $(this).data(\'value\');\r\n\r\n    $(\'#region\').text(selectValue);\r\n    selectedOptions.region = selectValue;\r\n    fetchDataFromServer(selectedOptions);\r\n});\r\n\r\n$(\'a.rooms\').on(\'click\', function () {\r\n    var selectValue = $(this).data(\'value\');\r\n\r\n    $(\'#rooms\').text(selectValue);\r\n    selectedOptions.rooms = selectValue;\r\n    fetchDataFromServer(selectedOptions);\r\n});\r\n\r\n$(\'a.sortbyprice\').on(\'click\', function () {\r\n    // var selectValue = $(this).text();\r\n    // selectedOptions.sortbyprice = selectValue;\r\n    selectedOptions.sortbyprice = \'asc\';\r\n    fetchDataFromServer(selectedOptions);\r\n});\r\n\r\nfunction fetchDataFromServer(options) {\r\n    $.ajax({\r\n        type: \'GET\',\r\n        url: \'/home\',\r\n        data: options,\r\n        success: function (response) {\r\n            if (response.error) {\r\n                // sweetAlert("Oops...", response.data, "error");\r\n                console.error(response.error);\r\n            } else {\r\n                console.log(response);\r\n                // I assume the data structure of the response is something like\r\n                // var reponse = {\r\n                //     data: [\r\n                //         {\r\n                //             price: 123,\r\n                //             rooms: \'1DK\',\r\n                //             region: \'\xe9\x96\xa2\xe8\xa5\xbf\'\r\n                //         },\r\n                //         ......\r\n                //     ]\r\n                // }\r\n                // This is an example function for updating the UI\r\n                // You can replace this function according to your needs\r\n                updateDisplay(displayList, response.data);\r\n            }\r\n        },\r\n        error: function (html, status) {\r\n            console.log(html.responseText);\r\n            console.log(status);\r\n        }\r\n    });\r\n}\r\n\r\nfunction updateDisplay(node, data) {\r\n    // build the html for the node(<ol> tag)\r\n    var template = data.reduce(function (acc, item) {\r\n        return acc + \'<li><p>Region: \' + item.region + \'</p><p>Price: \' + item.price + \'</p><p>Rooms: \' + item.rooms + \'</p></li>\';\r\n    }, \'\');\r\n\r\n    // add the template to the node(<ol> tag)\r\n    node.empty();\r\n    node.append(template);\r\n}
Run Code Online (Sandbox Code Playgroud)\r\n
#filter-wrapper {\r\n    margin-top: 15px\r\n}\r\n\r\n/*\r\n *  I added this line for demo purpose\r\n *  Not sure whether you\'ll need this in your app\r\n *  Feel free to remove this\r\n */\r\n#filter-wrapper::after {\r\n    content: \'\';\r\n    clear: both;\r\n    display: block;\r\n}\r\n\r\n#filter-wrapper ul {\r\n    list-style: none;\r\n    position: relative;\r\n    float: left;\r\n    margin: 0;\r\n    padding: 0\r\n}\r\n\r\n#filter-wrapper ul a {\r\n    display: block;\r\n    color: #333;\r\n    text-decoration: none;\r\n    font-weight: 700;\r\n    font-size: 12px;\r\n    line-height: 32px;\r\n    padding: 0 15px;\r\n    font-family: "HelveticaNeue", "Helvetica Neue", Helvetica, Arial, sans-serif\r\n}\r\n\r\n#filter-wrapper ul li {\r\n    position: relative;\r\n    float: left;\r\n    margin: 0;\r\n    padding: 0\r\n}\r\n\r\n#filter-wrapper ul li.current-menu-item {\r\n    background: lightblue;\r\n}\r\n\r\n#filter-wrapper ul li:hover {\r\n    background: #f6f6f6\r\n}\r\n\r\n#filter-wrapper ul ul {\r\n    display: none;\r\n    position: absolute;\r\n    top: 100%;\r\n    left: 0;\r\n    background: #fff;\r\n    padding: 0\r\n}\r\n\r\n#filter-wrapper ul ul li {\r\n    float: none;\r\n    width: 200px\r\n}\r\n\r\n#filter-wrapper ul ul a {\r\n    line-height: 120%;\r\n    padding: 10px 15px\r\n}\r\n\r\n#filter-wrapper ul ul ul {\r\n    top: 0;\r\n    left: 100%\r\n}\r\n\r\n#filter-wrapper ul li:hover>ul {\r\n    display: block\r\n}
Run Code Online (Sandbox Code Playgroud)\r\n
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>\r\n<div id="filter-wrapper">\r\n    <ul>\r\n        <li><a class="sortbyprice" href="javascript:" data-value="sortbyprice">Cheapest</a></li>\r\n        <li class="dropdown">\r\n            <a href="#" id="rooms">\xe9\x96\x93\xe5\x8f\x96\xe3\x82\x8a</a>\r\n            <ul class="init" name="rooms">\r\n                <li><a class="rooms" href="javascript:" data-value="1DK">1DK</a></li>\r\n                <li><a class="rooms" href="javascript:" data-value="2LDK">2LDK</a></li>\r\n                <li><a class="rooms" href="javascript:" data-value="3LDK">3LDK</a></li>\r\n            </ul>\r\n        </li>\r\n\r\n        <li class="dropdown">\r\n            <a href="#" id="region">\xe3\x82\xa8\xe3\x83\xaa\xe3\x82\xa2</a>\r\n            <ul class="init" name="region">\r\n                <li><a class="region" href="javascript:" data-value="\xe9\x96\xa2\xe8\xa5\xbf">\xe9\x96\xa2\xe8\xa5\xbf</a></li>\r\n                <li><a class="region" href="javascript:" data-value="\xe9\x96\xa2\xe6\x9d\xb1">\xe9\x96\xa2\xe6\x9d\xb1</a></li>\r\n                <li><a class="region" href="javascript:" data-value="\xe5\x8c\x97\xe6\xb5\xb7\xe9\x81\x93">\xe5\x8c\x97\xe6\xb5\xb7\xe9\x81\x93</a></li>\r\n            </ul>\r\n        </li>\r\n    </ul>\r\n</div>\r\n\r\n<div id="display-wrapper">\r\n    <ol></ol>\r\n</div>
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n