Home >Web Front-end >Front-end Q&A >How to add parameters in URL using jQuery
In front-end development, we often need to add parameters to the URL to implement some specific operations, such as paging, search, etc. By adding parameters, the backend can respond accordingly based on the parameters. This article will introduce how to use jQuery to add parameters to the URL.
In jQuery, we can use the $.param()
method to convert an object into a query string, and then add this string to the end of the URL. For example, we can declare a JavaScript object:
var params = { page: 1, filter: 'recommend', sort: 'desc' };
Then, we can use the $.param()
method to convert this object into a query string:
var qs = $.param(params); console.log(qs); // 'page=1&filter=recommend&sort=desc'
Now , we need to add this query string to the end of the URL. We can first get the current URL and then add the query string at the end of it.
var currentUrl = window.location.href; var newUrl = currentUrl.indexOf('?') > -1 ? currentUrl + '&' + qs : currentUrl + '?' + qs;
This code first gets the current URL, and then checks whether the URL already contains the query string. If the current URL already contains a query string, then we need to add new query parameters through the &
symbols at the end of the URL; if the current URL does not have a query string, we need to pass at the end of the URL. ?
symbols add query parameters.
Finally, we need to assign the new URL to the window.location.href
property:
window.location.href = newUrl;
In this way, we can add parameters. For example, we open the web page https://example.com
, and then execute the following code:
var params = { page: 1, filter: 'recommend', sort: 'desc' }; var qs = $.param(params); var currentUrl = window.location.href; var newUrl = currentUrl.indexOf('?') > -1 ? currentUrl + '&' + qs : currentUrl + '?' + qs; window.location.href = newUrl;
The final URL will become: https://example.com? page=1&filter=recommend&sort=desc
.
Summary:
When using jQuery, we can convert the JavaScript object into a query string through the $.param()
method, and then add this string to At the end of the URL, you can add parameters to the URL.
The above is the detailed content of How to add parameters in URL using jQuery. For more information, please follow other related articles on the PHP Chinese website!