Home > Articles > Open Source > Ajax & JavaScript

  • Print
  • + Share This
This chapter is from the book

Recipe: Passing HTTP Headers

If you need control over HTTP headers—for example, those used for caching—you can pass anything with the AJAX request. To test how this works, the test server from the first example returns a JSON string containing exactly the headers it received during the request.

Listing 5.9 passes a simple ETag header and displays the result returned from the test server.

Listing 5.9. Passing an ETag Header and Displaying the Returned Mirrored Headers from the Server

00 <!DOCTYPE html>
01
02 <html lang="en">
03 <head>
04   <title>The headers property</title>
05 </head>
06 <body>
07
08 <h2>Press the button to perform the request.</h2>
09
10 <button id="trigger">GET</button>
11 <br>
12 <div id="target">
13
14
15 <script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
16
17 <script>
18 // please externalize this code to an external .js file
19 $(document).ready(function() {
20
21   $('#trigger').click(function() {
22
23     $.ajax({url: 'return-http-headers',
24         headers : {
25             ETag: '12345'
26       }
27     })
28     .done(function(data, xhr) {
29       $('#target').append(
30         $.map(data.headers, function(i, name) {
31             return name + ' = '+ data.headers[name] + '<br/>';
32           })
33          .join(' ')
34       );
35     })
36     .fail(function(xhr, text, error) {
37       $('#target').append('Failed unexpectedly');
38     });
39   });
40
41 });
42 </script>
43 </body>
44 </html>

The test server returns a little bit more than just the HTTP headers, which might be useful for different tests such as ETag configuration, compression support (gzip, deflate), and even agent identification.

  • + Share This
  • 🔖 Save To Your Account