简体   繁体   English

jQuery修改基于IF的URL?

[英]Jquery to modify URL based on an IF?

I have a URL that does a filter and spits out some products the structure looks like below: 我有一个进行过滤的网址,并吐出一些产品,其结构如下所示:

/Products/Catalogue/tabid/102/andmode/1/Default.aspx?catfilter=185,223

Now on this there is a sort function and if I was to use this with out filtering as above the URL would look like the below: 现在,这里有一个排序函数,如果我要像上面那样在不进行过滤的情况下使用它,URL将如下所示:

/Products/Catalogue.aspx?orderby=price&desc=1&psize=9

If I currently try and filter and then sort, the sort overwrites myfilter, so the filter becomes null and void. 如果我当前尝试过滤并进行排序,则排序会覆盖myfilter,因此过滤器将变为无效。

So what I need it do is be aware that IF i have a filter then append the sorting after 'catfilter=' part in the URL so the URL would then look like 因此,我需要做的是知道,如果我有一个过滤器,然后在URL的'catfilter ='部分之后追加排序,则UR​​L看起来像

/Products/Catalogue/tabid/102/andmode/1/Default.aspx?catfilter=8,188&orderby=man&desc=0&psize=36

The gotcha is that there is not always going to be a filter added in which case the URL would be: 需要注意的是,在这种情况下,URL不一定是要添加的过滤器:
/Products/Catalogue.aspx /Products/Catalogue.aspx

<select id="listSort" class="NormalTextBox SortCatalogue" onchange="location = this.options[this.selectedIndex].value + '&' + getElementById('listLength')[getElementById('listLength').selectedIndex].value.split('?')[1] + document.getElementById('searchstrdiv').innerHTML.replace('amp;','');">
    <option value="?orderby=name&amp;desc=0&amp;">Sort by</option>
    <option value="?orderby=price&amp;desc=0">Lowest price</option>
    <option value="?orderby=price&amp;desc=1">Highest price</option>
    <option value="?orderby=man&amp;desc=0">Brand A-Z</option>
    <option value="?orderby=man&amp;desc=1">Brand Z-A</option>
    <option value="?orderby=name&amp;desc=0">Title A-Z</option>
    <option value="?orderby=name&amp;desc=1">Title Z-A</option>
    <option value="?orderby=ref&amp;desc=0">Code asc</option>
    <option value="?orderby=ref&amp;desc=1">Code desc</option>
</select>
<span style="text-align:right">Page size</span>
<select id="listLength" class="NormalTextBox PageLength" onchange="location = this.options[this.selectedIndex].value + '&' + getElementById('listSort')[getElementById('listSort').selectedIndex].value.split('?')[1] + document.getElementById('searchstrdiv').innerHTML.replace('amp;','');">
    <option value="?psize=9&foo">Page size</option>
    <option value="?psize=6">6 per page</option>
    <option value="?psize=9">9 per page</option>
    <option value="?psize=18">18 per page</option>
    <option value="?psize=36">36 per page</option>
</select>

<script type="text/javascript">

    var searchString = window.location.search.substring(1);
    var i, val;
    var params = searchString.replace('?','&').split('&');
    var pgsize,pgorder,pdesc,searchstr; 
    pgsize = 9;
    pgorder = 'name';
    pdesc = 0;
    searchstr='';
    for (i=0;i<params.length;i++) {
        val = params[i].split('=');
        if(val[0]== "psize")
            pgsize=val[1];
        else if(val[0]== "orderby")
            pgorder=val[1];
        else if(val[0]== "desc")
            pdesc=val[1];
        else if((val[0]).toLowerCase()== "search") { 
            searchstr=val[1]; 
        }
    }
    document.getElementById('listLength').value='?psize=' + pgsize;
    document.getElementById('listSort').value ='?orderby=' + pgorder + '&desc=' + pdesc;

    if(searchstr!='') {
        searchstr =decodeURIComponent(searchstr.replace(/\+/g, '%20'));
        document.getElementById('searchstrdiv').innerHTML= '&search=' + searchstr ;
        document.getElementById('searchtxthdrleft').innerHTML= 'Results for "' ;
        document.getElementById('searchtxthdrright').innerHTML= '"' ;
        document.getElementById('searchtxt').innerHTML = searchstr;
    }
 </script>

Ok lets take a step back from the problem. 好的,让我们从问题中退后一步。 I think you need to add a bit more structure instead of haphazardly adding and removing bits of url code here and there :) 我认为您需要添加更多的结构,而不是随意在URL的各处添加和删除一些URL代码:)

You have tagged the post as jQuery so i'm going to use that although you haven't actually used it in your posted code. 您已将帖子标记为jQuery,因此尽管您实际上并未在发布的代码中使用过它,但我将使用它。

The whole idea is going to be around creating a JavaScript object and using it as a lightweight dictionary , and the jQuery .param() function which will encode it for us at the end. 整个想法是围绕创建一个JavaScript对象并将其用作轻量级字典 ,以及最后将为我们编码的jQuery .param()函数

Lets change the markup to this: 让我们将标记更改为此:

<select id="listSort" class="NormalTextBox SortCatalogue">
    <option value="nameDesc">Sort by</option>
    <option value="priceAsc">Lowest price</option>
    <option value="priceDesc">Highest price</option>
    <option value="manAsc">Brand A-Z</option>
    <option value="manDesc">Brand Z-A</option>
    <option value="nameAsc">Title A-Z</option>
    <option value="nameDesc">Title Z-A</option>
    <option value="refAsc">Code asc</option>
    <option value="refDesc">Code desc</option>
</select>
<span style="text-align:right">Page size</span>
<select id="listLength" class="NormalTextBox PageLength">
    <option value="9">Page size</option>
    <option value="6">6 per page</option>
    <option value="9">9 per page</option>
    <option value="18">18 per page</option>
    <option value="36">36 per page</option>
</select>
<input type="text" id="searchstr">
<button id="searchbutton">Search!</button>

As you will see I've also thrown in a textbox and a button as you refer to searchstr in your code. 如您所见,在代码中引用searchstr ,我还抛出了一个文本框和一个按钮。

Instead of encoding and extracting we are just going to store some parseable values in the select options. 与其编码和提取,不如在选择选项中存储一些可解析的值。 We're also going to use an unobtrusive javascript technique by using the ID to attach an onchange handler rather than injecting the javascript into the markup (this will be added later on). 我们还将通过使用ID来附加onchange处理程序,而不是将javascript注入标记中来使用不引人注意的javascript技术(稍后会添加)。

Now we need to write some JavaScript code that can build us a querystring. 现在,我们需要编写一些JavaScript代码以构建查询字符串。 Instead of directly building a querystring though we will be making a javascript object. 尽管我们将创建一个javascript对象,而不是直接构建一个查询字符串。 Then later on that will be used to generate the query string. 然后,稍后将用于生成查询字符串。

I've written a search function that just displays the query string we generated rather than redirect the user. 我编写了一个搜索功能,该功能仅显示我们生成的查询字符串,而不是重定向用户。

I've also added in some event handlers so this is triggered as your code was triggering. 我还添加了一些事件处理程序,因此在您的代码被触发时会被触发。

function getFiltersAsQueryString() {
    var $listSort = $("#listSort"),
        $listLength = $("#listLength"),
        $searchQuery = $("#searchstr");
        queryStringDict = {};

    // extract page size
    queryStringDict["psize"] = $listLength.find("option:selected").val();    

    // extract sort order and direction
    var selectedItem = $listSort.find("option:selected").val();    
    queryStringDict["orderby"] = /^[a-z]*/.exec(selectedItem)[0];
    queryStringDict["desc"] = /Desc$/.exec(selectedItem) == "Desc" ? 1 : 0;

    // extract search
    queryStringDict["search"] = $searchQuery.val();

    return $.param(queryStringDict);
}

function searchWithFilters() {
    // normally you would do a window.location here to redirect
    alert(getFiltersAsQueryString());
}

$(document).ready(function () {
    // wire up our handlers
    $("#listSort").change(searchWithFilters);
    $("#listLength").change(searchWithFilters);
    $("#searchbutton").click(searchWithFilters);
});

And then at the end of the day when you put all this together you get this: 最后,当您将所有这些放在一起时,您将得到:

I don't think this is quite a complete solution yet. 我认为这还不是一个完整的解决方案。

  1. Need to add in the cat filter 需要添加猫过滤器
  2. Probably want to preselect the controls based on the query string? 可能想基于查询字符串预先选择控件?

I just wanted to post this to see if its going in the right direction. 我只想发布此消息,以查看其是否朝着正确的方向前进。

Hugly helpful thank you, ended up going with this some JS and Jquery in up to come up with the complete solution: 谢谢您的帮助,最后提供了一些JS和Jquery来提出完整的解决方案:

<script type="text/javascript">
var searchString = window.location.search.substring(1);
var i, val;
var params = searchString.replace('?','&').split('&');
var pgsize,pgorder,pdesc,searchstr,catfilter;
pgsize = 9;
pgorder = 'name';
pdesc = 0;
searchstr='';
for (i=0;i<params.length;i++) {
val = params[i].split('=');
if(val[0]== "psize")
pgsize=val[1];
else if(val[0]== "orderby")
pgorder=val[1];
else if(val[0]== "desc")
pdesc=val[1];
else if(val[0]== "catfilter")
catfilter=val[1];
else if((val[0]).toLowerCase()== "search")
{ searchstr=val[1]; }
}
document.getElementById('listLength').value='?psize=' + pgsize;
document.getElementById('listSort').value ='?orderby=' pgorder '&desc=' + pdesc;
if(searchstr!='')
{
searchstr =decodeURIComponent(searchstr.replace(/\+/g, '%20'));
document.getElementById('searchstrdiv').innerHTML= '&search=' + searchstr ;
document.getElementById('searchtxthdrleft').innerHTML= 'Results for "' ;
document.getElementById('searchtxthdrright').innerHTML= '"' ;
document.getElementById('searchtxt').innerHTML = searchstr;
}

if(catfilter)
{
document.getElementById('searchstrdiv').innerHTML=                 document.getElementById('searchstrdiv').innerHTML + '&catfilter=' + catfilter ;
}

</script>

<script type="text/javascript"> 
$(document).ready(function(){

$('.SortCatalogue').removeAttr('onchange');
$('.SortCatalogue').change(function() {newURL();});
$('.PageLength').removeAttr('onchange');
$('.PageLength').change(function() {newURL();});

function newURL()
{

var newParams = document.getElementById('listSort')    [document.getElementById('listSort').selectedIndex].value + '&amp;' +     document.getElementById('listLength')    [document.getElementById('listLength').selectedIndex].value.split('?')[1] +     document.getElementById('searchstrdiv').innerHTML.replace('amp;','');

var oldPathname = location.pathname;
oldPathname = oldPathname.replace('/desc/','/').replace('/orderby/', '/');

document.location.href = oldPathname + newParams;

}

});
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM