Home >Web Front-end >JS Tutorial >How to add query string parameters to Fetch GET requests?

How to add query string parameters to Fetch GET requests?

Linda Hamilton
Linda HamiltonOriginal
2024-10-26 00:46:021053browse

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>

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>

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!

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