Is it possible to do a HTTP Head request solely using an XMLHTTPRequest in JavaScript?
My motivation is to conserve bandwidth.
If not, is it possible to fake it?
HEAD Http Method HEAD is a request method supported by HTTP used by the World Wide Web. The HEAD method asks for a response identical to that of a GET request, but without the response body. This is useful for retrieving meta-information written in response headers, without having to transport the entire content.
To make a HEAD request with Curl, you need to use the -I or --head command-line parameter. The -I command-line parameter tells Curl to send an HTTP HEAD request to receive only HTTP headers. The HEAD request is very similar to a GET request, except that the server only returns HTTP headers without a response body.
What's AJAX? AJAX stands for Asynchronous JavaScript And XML. In a nutshell, it is the use of the XMLHttpRequest object to communicate with servers. It can send and receive information in various formats, including JSON, XML, HTML, and text files.
XHR - XML Http Request XHR is a JavaScript object that is used to transfer data between a web browser and a web server. XHR is often used to request and receive data for the purpose of modifying a web page.
Easy, just use the HEAD method, instead of GET or POST:
function UrlExists(url, callback) { var http = new XMLHttpRequest(); http.open('HEAD', url); http.onreadystatechange = function() { if (this.readyState == this.DONE) { callback(this.status != 404); } }; http.send(); }
This is just a short example to show how to use the HEAD method. Production code may need more fine-grained callbacks for different result states (success, failure, timeout), and may use different event handlers (onload
, onerror
and ontimeout
rather than onreadystatechange
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With