2013-06-25 33 views
1

我有一個過濾器和產品列表(id,name,creation_date)。Rails 3:使用AJAX請求更新URL參數

我可以按ID,名稱或creation_date進行過濾。有了AJAX請求,我更新了一個內容分區......但顯然這個URL沒有改變。

如何將PARAMS添加到URL?例如:

localhost:3000/dashboard/catalog?name=radio&?date_creation=23-06-2013 

我知道history.pushState(HTML5)存在......但我需要我的應用程序在HTML4瀏覽器IE9一樣工作。

我試過Wiselinks(https://github.com/igor-alexandrov/wiselinks)它使用History.js,但它不使用AJAX請求。

任何想法?

感謝

+2

如果用ajax(通過執行'window.location.href ='new/url'')更改URL,頁面將重新加載。您需要在'#'之後向URL添加參數,因此您的URL將如下所示:'localhost:3000/dashboard/catalog#name = radio&date_creation = 23-06-2013' – MrYoshiji

回答

0

你正在做一些AJAX調用手段,您必須調用單選按鈕變化

所以我假設了AJAX的一部分,你已經使用單選按鈕和單選按鈕的名稱做了是'choose_product'

您可以在視圖中添加隱藏字段,您可以在其中存儲當前日期。

<div id='parentDiv'> 
<%= hidden_field_tag 'current_date', Time.now.strftime('%d-%m-%Y') %> 
Your radio button code 
</div> 

在javascript中添加以下代碼。這只是一個不完整的解決方案。

$(document).ready(function(){ 
var showProducts = function(){ 
    $("#parentDiv").on('click', "input[name='choose_product']", function(){ 
    var ajax_url = 'localhost:3000/dashboard/catalog'; 
    var url_param = ''; 

    switch($(this).val()){ 
    case 'creation_date': 
    var param_date = $('#current_date').val(); 
    url_param = '?name=radio&date_creation=' + param_date;  
    break; 
    case 'name': 
    // Your code goes here 
    default: 
    //Your code goes here 
    } 

    // Here you will get the modified url dynamically 
    ajax_url += url_param 

    $.ajax({ 
    url: ajax_url, 
    // your code goes here 
    }); 
    }); 
} 

showProducts(); 
}); 
0

大量的時間已經過去了,但它可能是有用的。 代碼也被更新,所以如果你有一個以上的ajax \ remote鏈接,你將能夠合併多個url的params。 根據user1364684 answer和this針對聯合網址。

# change ".someClassA" or "pagination" to the a link of the ajax elemen 
$(document).on('click', '.someClassA a, .pagination a', function(){ 
    var this_params = this.href.split('?')[1], ueryParameters = {}, 
     queryString = location.search.substring(1), re = /([^&=]+)=([^&]*)/g, m; 

    queryString = queryString + '&' + this_params; 

    #Creates a map with the query string parameters 
    while m = re.exec(queryString) 
     queryParameters[decodeURIComponent(m[1])] = decodeURIComponent(m[2]); 

    url = window.location.href.split('?')[0] + "?" + $.param(queryParameters); 

    $.getScript(url); 
    history.pushState(null, "", url); 

    return false; 
}); 

# make back button work 
$(window).on("popstate", function(){ 
    $.getScript(location.href); 
});