Home > Web Front-end > JS Tutorial > body text

How to add query string parameters to Fetch GET requests?

Linda Hamilton
Release: 2024-10-26 00:46:02
Original
939 people have browsed it

How to add query string parameters to Fetch GET requests?

Query String Addition in Fetch GET Requests

While exploring the Fetch API's query string capabilities, a developer aims to pass parameters to GET requests using a method akin to jQuery's $.ajax().

Solution

The new Fetch API employs URLSearchParams to tackle query string addition. This object offers a convenient way to build and modify query string parameters.

<code class="javascript">fetch('https://example.com?' + new URLSearchParams({
    foo: 'value',
    bar: 2,
}).toString())</code>
Copy after login

The URLSearchParams.toString() method encodes the parameter object into an appropriately formatted query string.

Alternatively, you can omit the .toString() call, as JavaScript automatically coerces non-string objects to strings when concatenated with strings. Note that this approach requires a deeper understanding of JavaScript.

Complete Example

Here's a comprehensive example with query parameters:

<code class="javascript">async function doAsyncTask() {
  const url = (
    'https://jsonplaceholder.typicode.com/comments?' +
    new URLSearchParams({ postId: 1 }).toString()
  );

  const result = await fetch(url)
    .then(response => response.json());

  console.log('Fetched from: ' + url);
  console.log(result);
}

doAsyncTask();</code>
Copy after login

The above is the detailed content of How to add query string parameters to Fetch GET requests?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!