使用dropdown和URL参数过滤json

时间:2015-07-22 18:29:00

标签: javascript jquery html json drop-down-menu

好的,我有一个JSON,我有一个由JSON填充的表。我希望能够按类别进行过滤(我已经可以使用下拉菜单进行过滤)。棘手的部分是,我希望能够更改URL并显示正确的过滤器。

例如:

'http://myexample.com/timerPage.html'会将某人直接带到主页面,不会过滤。

'http://myexample.com/timerPage.html?filter=booklet'会将某人带到仅显示小册子的已过滤页面。

此外,当我点击下拉菜单并转到“小册子”时,它会将网址更改为“http://myexample.com/timerPage.html?filter=booklet

所以基本上我只是希望能够更改URL并让它影响显示哪个下拉项并运行它的代码。 这可能吗?这是我到目前为止的代码:

JSON SNIPPET

[
{
    "daily_percentile_90th": 32603,
    "daily_average": 26045.4,
    "timerName": "Booklet:Landscape"
},
{
    "daily_percentile_90th": 32603,
    "daily_average": 26045.4,
    "timerName": "Booklet:Horizon"
},
{
    "daily_percentile_90th": 9198.3,
    "daily_average": 5563.67,
    "timerName": "Search:DownloadImage"
},
{
    "daily_percentile_90th": 3299.9,
    "daily_average": 2867.13,
    "timerName": "Search:Results"
}
]

HTML

<select id="dropdown" onclick="filter(this);">
   <option value="all" href="all" selected>All</option>
   <option value="booklet" href="booklet">Booklet</option>
   <option value="search" href="search">Search</option>
</select>

JAVASCRIPT

/*******************************************************************
        THIS GRABS THE FILTER AND CHANGES THE URL
*******************************************************************/
window.filter = function(choice){
if(choice.value=="all"){
    window.location.href = "?filter=all";
    clearTable();
    filterAll();
}
else if (choice.value=="booklet"){
    window.location.href = "?filter=booklet";
    bounds = "Booklet";
    clearTable();
    filterByTimerName(bounds);
}
else if(choice.value == "search"){
    window.location.href = "?filter=search";
    bounds = "Search";
    clearTable();
    filterByTimerName(bounds);
}
}


/*******************************************************************
                   THIS DOES THE ACTUAL FILTERING
*******************************************************************/
function filterByTimerName(filter){
$.getJSON('http://myJson.com/latestJson/', function(jsonData){
    var filtered = [];

    for (var i = 0; i < jsonData.length; i++) {
        // if 'timerName' begins with whatever 'filter' is
        if (jsonData[i].timerName.substring(0, filter.length) === filter) {
            filtered.push(jsonData[i]);
        }
    }

    return filtered;
});
}

提前感谢您的帮助!!! :)

0 个答案:

没有答案