Home  >  Article  >  Web Front-end  >  How to Retrieve \"GET\" Request Parameters in JavaScript?

How to Retrieve \"GET\" Request Parameters in JavaScript?

Linda Hamilton
Linda HamiltonOriginal
2024-10-18 18:49:02838browse

How to Retrieve

Retrieving "GET" Request Parameters in JavaScript

In JavaScript, obtaining "GET" request parameters requires some processing to extract the data. While neither jQuery nor YUI! provide built-in functionality for this, you can utilize the following approaches:

Updated June 2021:

Modern browsers offer built-in APIs for manipulating URLs (URL) and query strings (URLSearchParams). These APIs should be favored unless supporting legacy browsers or Opera mini is a requirement.

Original Approach:

The "GET" request data resides within window.location.search. To access this data, parse the string using a regular expression:

<code class="javascript">function get(name) {
  if (name = (new RegExp('[?&]' + encodeURIComponent(name) + '=([^&]*)')).exec(location.search))
    return decodeURIComponent(name[1]);
}</code>

To retrieve a GET variable, simply invoke the get() function with the variable's name as a parameter:

<code class="javascript">get('foo'); // returns variable value or undefined</code>

The above is the detailed content of How to Retrieve \"GET\" Request Parameters in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn