Home >Web Front-end >JS Tutorial >How to add query string parameters to 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().
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.
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!