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.
fetch('https://example.com?' new URLSearchParams({
foo: 'value',
bar: 2,
}).toString())
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:
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();
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3