Datatables - how to pass search parameter in a url

ぐ巨炮叔叔 提交于 2019-12-03 14:57:47

You could simply have a function that reads your URL var and then filter the table. I imagine that you pass q=Firefox as your search

// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
 var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
        vars[key] = value;
    });
    return vars;

}

$(document).ready(function() {
    // Get the query from the url
    var query = getUrlVars()['q'];
    // create the table
    var oTable = $('#example').dataTable();
    // Filter it
    oTable.fnFilter( query, 2 );
});

Fiddle here http://fiddle.jshell.net/9CxYT/17/show/?q=Firefox

This is an old question, but it still pops up high when searching for a solution. Here's what I did to make it work.

$(document).ready( function() {
  
  // First, get the search parameter. Here I use example.com#search=yourkeyword
    var searchHash = location.hash.substr(1),
        searchString = searchHash.substr(searchHash.indexOf('search='))
		                  .split('&')[0]
		                  .split('=')[1];
  
  
  $('#example').dataTable( {
    "oSearch": { "sSearch": searchString }
  } );
} )

Here is what I did to get it to work:

The first part from @Ibriquet gets the GET parameters from the url, I didn't change that. Quite possibly there is a nicer way to do this, but I didn't research that.

// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
 var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
        vars[key] = value;
    });
    return vars;

}

For the second part I included this within the $('#tablename').DataTable( { here, right after the column setup }

      initComplete: function() {
        this.api().search(getUrlVars()['search']).draw();        
      },

This puts anything after the ?search= and before any & in your url into the search field.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!