Home > Web Front-end > JS Tutorial > How to Retrieve \'GET\' Request Parameters in JavaScript?

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

Linda Hamilton
Release: 2024-10-18 18:49:02
Original
936 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template