Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTTP HEAD Request in Javascript/Ajax?

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?

like image 363
EoghanM Avatar asked Dec 02 '08 11:12

EoghanM


People also ask

What is HTTP HEAD request?

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.

How do I make a HTTP HEAD request?

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 is AJAX request in JavaScript?

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.

What is HTTP request in JavaScript?

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.


1 Answers

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).

like image 177
doekman Avatar answered Sep 23 '22 18:09

doekman