jQuery向URL添加多个过滤器参数 [英] jQuery add multiple filter parameters to url

查看:116
本文介绍了jQuery向URL添加多个过滤器参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多组复选框用于过滤搜索结果.例如,搜索衬衫将把第一组作为颜色,其中包括黑色,蓝色,红色,第二组作为尺寸,其中包括诸如小,中,大.标准的东西...

在进行搜索并应用了过滤器之后,此示例的网址如下所示:

www.xzy.dev/search?keywords=shirt&colors=red,black&sizes=small,medium

这将返回与关键字搜索匹配的所有项目,并带有颜色(红色和黑色)和大小(中小)的过滤器.

我已经完成了所有的后端工作,但是在事情的前端方面我不是很好...

下面的代码几乎可以满足我的需求,但它对我的情况存在缺陷,下面将对此进行解释.

<script type="text/javascript">
      function GetFilters() {
          console.log("rom");
          $('input[type="checkbox"]').on('change', function (e) {
              var data = {},
                  fdata = [],
                  loc = $('<a>', { href: window.location })[0];
              $('input[type="checkbox"]').each(function (i) {
                  if (this.checked) {
                      if (!data.hasOwnProperty(this.name)) {
                          data[this.name] = [];
                      }
                      data[this.name].push(this.value);
                  }
              });
              // get the key
              var key = Object.keys(data)[0];
              // and the data
              // it works to without joining
              var fdata = key+"="+data[key].join(',');
              // and if you wanna strip the whitespaces
              // use fdata = fdata.replace(/\s/g,"");
              $.ajax({
                type: "POST",
                url: "/ajax/get",
                data: {
                      "_token": "{{ csrf_token() }}",
                      "fdata": fdata
                    },
                success: function (response) {
                  $('#d2d-results').html(response);
                }
              });
              if (history.pushState) {
                  history.pushState(null, null, loc.pathname + '?' + fdata);
              }
          });
      }
      window.onload = GetFilters;
  </script>

该代码在大多数情况下都起作用.当我单击一个复选框时,它会附加到URL并完成ajax请求.效果很好...

但是我所说的代码存在的问题是,当我取消选中最后一个复选框以删除最终过滤器时,它保留在url中,并引发错误:

Uncaught TypeError: Cannot read property 'join' of undefined
    at HTMLInputElement.<anonymous> (677)
    at HTMLInputElement.dispatch (jquery.min.js:3)
    at HTMLInputElement.q.handle (jquery.min.js:3)

第二,该代码仅在使用一个过滤器组时有效.如果我尝试从另一个过滤器组中单击一个复选框,而已经从第一个过滤器组中进行了选择,例如,如果已经选择了colors = red,black,则说明操作失败,并且由于明显的原因,因为代码似乎不允许它.

如何修改它以添加多个查询组?如何在我的颜色组中单击红色和黑色,在我的尺寸组中单击中小型,并显示网址:

www.xzy.dev/search?keywords=shirt&colors=red,black&sizes=small,medium

但是如果我不想指定颜色,还可以删除实际的查询吗?

www.xzy.dev/search?keywords=shirt&sizes=small,medium

解决方案

我认为您的问题是您总是只获得一个键(如果存在则不存在,则代码会因为未定义而中断). /p>

您应该遍历所有键,这样一来,即使没有键也很安全-fdata将保持为空.

<script type="text/javascript">
  function GetFilters() {
      $('input[type="checkbox"]').on('change', function (e) {
          var data = {},
              fdata = [],
              loc = $('<a>', { href: window.location })[0];
          $('input[type="checkbox"]').each(function (i) {
              if (this.checked) {
                  if (!data.hasOwnProperty(this.name)) {
                      data[this.name] = [];
                  }
                  data[this.name].push(this.value);
              }
          });
          // get all keys.
          var keys = Object.keys(data);
          var fdata = "";
          // iterate over them and create the fdata
          keys.forEach(function(key,i){
              if (i>0) fdata += '&'; // if its not the first key add &
              fdata += key+"="+data[key].join(',');
          });
          $.ajax({
            type: "POST",
            url: "/ajax/get",
            data: {
                  "_token": "{{ csrf_token() }}",
                  "fdata": fdata
                },
            success: function (response) {
              $('#d2d-results').html(response);
            }
          });
          if (history.pushState) {
              history.pushState(null, null, loc.pathname + '?' + fdata);
          }
      });
  }
  window.onload = GetFilters;

I have multiple groups of checkboxes that are used to filter search results. For example, a search for shirts would have group one as colors, which includes things like, black, blue, red and group two as sizes, which includes things like, small, medium, large. Standard stuff...

The url for this example would look like the following, after a search is made, and the filters are applied:

www.xzy.dev/search?keywords=shirt&colors=red,black&sizes=small,medium

This would return me all items that match the keyword search, with the filters of colors (red and black), and sizes (small and medium).

I have all of the backend done, but I am not very great when it comes to the front end of things...

The code below does just about what I want, except it has it's flaws for my situation which I've explained below.

<script type="text/javascript">
      function GetFilters() {
          console.log("rom");
          $('input[type="checkbox"]').on('change', function (e) {
              var data = {},
                  fdata = [],
                  loc = $('<a>', { href: window.location })[0];
              $('input[type="checkbox"]').each(function (i) {
                  if (this.checked) {
                      if (!data.hasOwnProperty(this.name)) {
                          data[this.name] = [];
                      }
                      data[this.name].push(this.value);
                  }
              });
              // get the key
              var key = Object.keys(data)[0];
              // and the data
              // it works to without joining
              var fdata = key+"="+data[key].join(',');
              // and if you wanna strip the whitespaces
              // use fdata = fdata.replace(/\s/g,"");
              $.ajax({
                type: "POST",
                url: "/ajax/get",
                data: {
                      "_token": "{{ csrf_token() }}",
                      "fdata": fdata
                    },
                success: function (response) {
                  $('#d2d-results').html(response);
                }
              });
              if (history.pushState) {
                  history.pushState(null, null, loc.pathname + '?' + fdata);
              }
          });
      }
      window.onload = GetFilters;
  </script>

The code works for the most part. When I click a checkbox, it appends to the url and the ajax request is done. Works great...

But the issues I am having with said code is that when I uncheck the last checkbox to remove the final filter, it stays in the url, and casts an error:

Uncaught TypeError: Cannot read property 'join' of undefined
    at HTMLInputElement.<anonymous> (677)
    at HTMLInputElement.dispatch (jquery.min.js:3)
    at HTMLInputElement.q.handle (jquery.min.js:3)

Second, the code only works when I use one filter group. If I try to click a checkbox from another filter group while a selection is already made from the first, for instance if colors=red,black are already selected, things fail, and for obvious reasons, because the code doesn't seem to allow it.

How can this be modified to add multiple query groups? How can I click red and black from my colors group and small and medium from my sizes group and have the url display:

www.xzy.dev/search?keywords=shirt&colors=red,black&sizes=small,medium

But also remove the actual query if I don't want to specify colors for instance?

www.xzy.dev/search?keywords=shirt&sizes=small,medium

解决方案

I think your problem is that you are always only getting only one key ( if exists if it doesn't exist then the code breaks because its undefined).

you should iterate over all the keys and in that way you are also safe if you got no keys - fdata will remain empty.

<script type="text/javascript">
  function GetFilters() {
      $('input[type="checkbox"]').on('change', function (e) {
          var data = {},
              fdata = [],
              loc = $('<a>', { href: window.location })[0];
          $('input[type="checkbox"]').each(function (i) {
              if (this.checked) {
                  if (!data.hasOwnProperty(this.name)) {
                      data[this.name] = [];
                  }
                  data[this.name].push(this.value);
              }
          });
          // get all keys.
          var keys = Object.keys(data);
          var fdata = "";
          // iterate over them and create the fdata
          keys.forEach(function(key,i){
              if (i>0) fdata += '&'; // if its not the first key add &
              fdata += key+"="+data[key].join(',');
          });
          $.ajax({
            type: "POST",
            url: "/ajax/get",
            data: {
                  "_token": "{{ csrf_token() }}",
                  "fdata": fdata
                },
            success: function (response) {
              $('#d2d-results').html(response);
            }
          });
          if (history.pushState) {
              history.pushState(null, null, loc.pathname + '?' + fdata);
          }
      });
  }
  window.onload = GetFilters;

这篇关于jQuery向URL添加多个过滤器参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆