问题
I have a javascript/springboot project that has a search page. On the page you can select multiple filter options then hit search. Here's a simplified demo of that page on fiddle. I want to be able to take all the inputted filter options and put them in the URL so users can easy bookmark their frequently used searches. I was thinking about following google's querying pattern like so:
https://www.google.com/search?q=this+is+a+test+search&oq=this+is+a+test+search&aqs=chrome..69i57j0.2487j0j9&sourceid=chrome&ie=UTF-8
Where the URL follows the pattern search?q=<query string>
. But I'm not sure how I would follow this given my query needs of having different search categories (Location, Type, Color) and multiple filter options within each type.
Is this the better url parameter pattern to follow or is there a better way? If it is the best pattern, how would I go about implementing this in javascript? Because I need to collect the search filters and post a request to a controller method to process the search.
Update 1: I would think the best way to implement this would be to have a URL like so:
https://www.mywebsite.com/search?location=Alabama&location=Wyoming&type=SUV&color=White&color=Black&color=Green
OR
https://www.mywebsite.com/search?location=Alabama,Wyoming&type=SUV&color=White,Black,Green
And a controller to receive that request like so:
@RequestMapping(value = {"/search/"}, method = RequestMethod.GET)
public String search(@RequestParam Map<String,String> searchFilters){
/**
* searchFilters["location"] = [Alabama, Wyoming]
* searchFilters["type"] = [SUV]
* searchFilters["color"] = [White, Black, Green]
**/
}
But I'm not sure that would actually work....
回答1:
You can use multiple parameters in your query string with comma-separated values.
function getValues(id) {
return $("#" + id).val().join(",");
}
$("button").click(function() {
location.href = "search" +
"?loc=" + getValues("e1") +
"&type=" + getValues("e2") +
"&col=" + getValues("e3");
})
Here's a fiddle to see an example. You can then retrieve each parameter individually and split the values around the commas.
If your options could potentially contain commas, you should either escape them or use a different URL-safe character to delimit the values.
来源:https://stackoverflow.com/questions/47211632/javascript-advanced-search-with-parametrized-url