|Written by Ian Elliot|
|Monday, 16 October 2017|
Page 2 of 2
FormData, Get & Post
The most common fetch operations that go beyond a simple get are get with a query string and posting form data. Let’s see how to do both of these tasks.
The data that we want to send could come from anywhere, but a traditional form element is simple and common:
Now all we need is to handle the submit event:
The FormData object creates a set of key/value pairs from the form with the keys being the id’s and the values being what ever the user entered. This is then converted to a query string using the searchParams method of the URL object. Finally we build a request object specifying a GET and perform the fetch.
The url is something like:
assuming that the user entered Mickey Mouse as the first and last names. This is sent to the server, which will process it and do whatever is appropriate with the data before returning a response. This can either be collected using a command like:
or we can opt to ignore it.
Sending form data using a POST is even easier as we can send a FormData object without having to convert it:
The formdata will be unpacked into the body and sent to the server. A Content header is also set automatically so that the server can check the format of the data.
Notice that as a Request object has a body you can access it using the same methods as in a Response object. As for the Response object, once you have used the body data you can’t use it a second time. You can, of course, clone it if you really want to treat it as different formats.
This is about all there is to know about the new APIs. There are still things to learn and implement, but these problems are not any different from using other methods of transferring data. Currently the facilities offered by fetch aren’t as extensive as what you will find in, say, jQuery, but it has to be taken into account that fetch is the way of the future.
There are also some new features in the Fetch API that help with the problem of canceling and controlling a request, the Abort API, but these aren’t standardized as yet. In addition, it is worth knowing that you can access the lower level data streams used to access the body data. This offers the possibility of creating very sophisticated processing. However, in most cases the standard formatted stream readers are enough.
Now Available as a Print Book:
You can buy it from: Amazon
or email your comment to: email@example.com
|Last Updated ( Friday, 08 February 2019 )|