HTTP defines GET as retrieving information from the Request-URI. GET is also a idempotent method. That's to say, the results of identical GET requests are the same as that of a single request. Because GET is used to retrieve information, it doesn't alter the server state.
When using GET to submit a traditional form, the request parameters are shown in the location bar and the page is refreshed. If using asynchronous objects to do a GET request, the request parameters aren't shown in the location bar, so users can't save request parameters in their bookmark directly.
When using an asynchronous object to send a GET request with parameters, the query string is appended to the second url argument of open, and then the send function is called with a null argument. An example is as follow:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN">
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type">
<script type="text/javascript">
window.onload = function() {
var xhr = window.XMLHttpRequest &&
(window.location.protocol !== 'file:'
|| !window.ActiveXObject) ?
function() {
return new XMLHttpRequest();
} :
function() {
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch(e) {
throw new Error('XMLHttpRequest not supported');
}
};
document.getElementById('category').onchange = function() {
var request = xhr();
request.onreadystatechange = function() {
if(request.readyState === 4) {
if(request.status === 200) {
document.getElementById('book').innerHTML =
request.responseText;
}
}
};
request.open('GET', 'GET-1.php?category=' + this.value +
'&time=' + new Date().getTime()); // Avoid caching a GET request
request.send(null);
};
};
</script>
</head>
<body>
Book: <br>
<select id="category">
<option>-- Category --</option>
<option value="theory">Theory</option>
<option value="language">Language</option>
<option value="web">Web</option>
</select><br><br>
Buy: <div id="book"></div>
</body>
</html>
The above example demonstrates how to implement cascading drop down lists. The items of the second drop down list depend on the selected item of the first one. We don't hard code items of the second drop down list, yet generate them according to the request parameter of the first one. For example, if the request parameter is 'category=theory', the returned HTML fragment is as follow:
<select>
<option value="algorithm">Algorithm</option>
<option value="graphic">Computer Graphics</option>
<option value="pattern">Design Pattern</option>
</select>
<option value="algorithm">Algorithm</option>
<option value="graphic">Computer Graphics</option>
<option value="pattern">Design Pattern</option>
</select>
Of course, returning a HTML fragment isn't a good way since the server limits the client's page design. This example is only demonstrating how to send a GET request. We'll see other response formats, such as XML or JSON. They give clients flexibility in dealing with their own page design.
Another point to note is that, browsers, especially Internet Explorer, may cache a GET request if the url is the same. To avoid retrieving old data, you can append a time stamp to the url. A request with a different request won't be cached by browsers.
In the world of the web, this is always not the end of story. When sending a GET request, you should pay attention to encoding problems. URL has several reserved words, such as '/', '?', '@', a space character, etc. They are defined in RFC 3986. If you want to express these reserved words or non-ASCII characters, the '%HEXHEX' format should be used. For example, the url 'https://openhome.cc/add.jsp?url=http://caterpillar.onlyfun.net'should be written as follow:
http://opehome.cc/add.jsp?http%3A%2F%2Fcaterpillar.onlyfun.net
The three characters '://' are encoded into '%3A%2F%2F'.
In JavaScript, the encodeURIComponent function is used for encoding characters. Its encoding rules comply with RFC 3986. Before RFC 3986, however, HTTP has defined encoding rules for GET and POST. Basically, the encoding format is also '%HEXHEX', but the space character is encoded as '+', not '%20' in RFC 3986. When submitting a traditional form, browsers will automatically encode request parameters according to the specified encoding of the page, and the space character is encoded as '+'. If you send request parameters through asynchronous objects, you should do encoding by yourself.
After calling encodeURIComponent, you should replace '%20' with '+' to comply with the HTTP specification. What you should know is, JavaScript uses Unicode internally and UCS-2/UTF-16 is the implementation (There are some detail in the history. See the item 7 of Effective JavaScript book for more information). So, the string passed to encodeURIComponent should be UTF-8. After sending request parameters encoded by encodeURIComponent, the server should process the received string in UTF-8.
If asynchronous objects send a request without using encodeURIComponent to encode non-ASCII request parameters, like Traditional Chinese characters, how will asynchronous objects encode request parameters? This depends on browsers. So, it's suggested to use encodeURIComponent, and then replace '%20' with '+' before sending a request to avoid cross-browsers problems.
The following example is another demonstration about GET. If your input conflicts with an existing bookmark (there're two existing bookmarks, 'http://caterpillar.onlyfun.net' and 'https://openhome.cc'), an error message will be shown.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN">
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type">
<script type="text/javascript">
window.onload = function() {
var xhr = window.XMLHttpRequest &&
(window.location.protocol !== 'file:'
|| !window.ActiveXObject) ?
function() {
return new XMLHttpRequest();
} :
function() {
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch(e) {
throw new Error('XMLHttpRequest not supported');
}
};
function param(obj) {
var pairs = [];
for(var name in obj) {
var pair = encodeURIComponent(name) + '=' +
encodeURIComponent(obj[name]);
pairs.push(pair.replace('/%20/g', '+'));
}
return pairs.join('&');
}
document.getElementById('url').onblur = function() {
var request = xhr();
request.onreadystatechange = function() {
if(request.readyState === 4) {
if(request.status === 200) {
var message = '';
if(request.responseText === 'urlExisted') {
message = 'URL existed';
}
document.getElementById('message')
.innerHTML = message;
}
}
};
var params = param(
{ url : document.getElementById('url').value}
);
request.open('GET', 'GET-2.php?' + params +
'&time=' + new Date().getTime()); // Avoid caching a GET request
request.send(null);
};
};
</script>
</head>
<body>
Add a bookmark:<br>
URL: <input id="url" type="text">
<span id="message" style="color:red"></span><br>
Title: <input type="text">
</body>
</html>
If the URL already exists, a string 'urlExisted' will be returned. The message variable will be set as 'URL existed'.