-
- JavaScript: HTTP Requests (AJAX)
- Weather:多云 ,西南风 3-4级 ,最低气温21 ℃
- 2005-08-26
Field of Use
Lately, as more and more browsers integrated support of the JavaScript XMLHTTPRequest object, it suddenly became more and more popular. And not without reason, this method can come in very handy in lots of situations. What does it do? It allows you to send HTTP requests from the client to retrieve additional data after the (X)HTML page has been rendered. Things that benefit from it: Client-side form validation, conditional checkboxes/selectboxes, searches, server queries, shopping carts, etc.
The downside, however, is that you can only send the request to the originating domain only (so-called sandbox). So you will need for most of those things a server-side proxy script to take care of this problem. But don't worry, I'll provide sample PHP scripts as well.
About the term AJAX
More and more often the term "AJAX" is used for this technique. AJAX means "Asynchronous JavaScript and XML" and pretty much sums up what this is all about: Creating an asynchronous connection and retrieving XML/Text data.
Proof-of-Concept
Here is the basic code you need in order to use the object for GET/HEAD requests.
function myRequest(myUrl) { if(window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); // Gecko (Firefox, Moz), KHTML (Konqueror, Safari), Opera } else if(window.ActiveXObject) { xmlhttp = new ActiveXObject("MSXML2.XMLHTTP"); // Internet Explorer } else { return false; } xmlhttp.open("GET", myUrl, true); // Open a connection. Replace GET with HEAD in order to do a HEAD request. xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState == 4) { // Wait until everything is fetched! alert(xmlhttp.getAllResponseHeaders()); // Prints all teh response headers to the screen to see if it was successful // xmlhttp.responseText contains the contents of the response. } } xmlhttp.send(null); // send() is used to initiate the transfer. No actual data have to be sent in this case. }You can now easily call it with
POST Requestsonclick="myRequest('/index.html')".GET/HEAD requests are pretty easy to do so now we try to do a POST request. This will come in handy when we try to send a form from a document to the server later on.
function myRequest(myUrl) { var myText = "samplefield="+escape('sample value'); if(window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else if(window.ActiveXObject) { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } else { return false; } xmlhttp.open("POST", myUrl, true); xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); // sending it as encoded formdata xmlhttp.setRequestHeader("Content-length",myText.length); // we need to specify the length of the contents xmlhttp.setRequestHeader("Connection","close"); // Connection is to be closed after transfer xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState == 4) { // Wait until everything is fetched! alert(xmlhttp.getAllResponseHeaders()); } } xmlhttp.send(myText); // This time, we need to send the text. }View the GET/POST/HEAD example.
Using The Script
Example 1: Refreshing Content
Say, you have an area on your website you want to refresh regularly (like every 1 minute) or when the user clicks a button/link. But instead to refresh the whole website you only want to refresh a certain area (e.g. often used for online radio websites). XMLHTTPRequest could soon be your method of choice. Here's an example.
HTML Body: <p style="margin-top:40px;text-align:center;" onclick="refreshDate('/tutorials/js-request/refresh.php','date')">Click here to show/refresh the date!</p> <p style="margin-top:40px;text-align:center;" onclick="refreshDate('/tutorials/js-request/refresh.phps','date')">Click here to get the php source code!</p> <p id="date"></p> JavaScript: function refreshDate(myUrl,myField) { var Field = document.getElementById(myField); // selects the given element if(window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else if(window.ActiveXObject) { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } else { return false; } xmlhttp.open("GET", myUrl, true); xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState == 4) { Field.innerHTML = xmlhttp.responseText; // puts the result into the element } } xmlhttp.send(null); }Example 2: Preview Posts (e.g. Forumposts)
Some forums have the nice functions to preview postings before sending them. But why having to refresh the whole page if you could just update the preview?
HTML Body: <form action="index.php5" name="editor_form" method="post"> <fieldset> <legend>Content Editor</legend> <label for="text_plain">Insert plaintext here:</label> <textarea name="text_plain" id="text_plain" cols="75" rows="20"> http://test.com/testurl [email protected] </textarea> <p><input name="submit" type="submit" value="Submit" /></p> </fieldset> </form> <p><a href="#" onclick="refreshPreview('text_plain','preview','/tutorials/js-request/preview.php');return false;">Refresh Preview</a></p> <p><a href="#" onclick="refreshPreview('text_plain','preview','/tutorials/js-request/preview.phps');return false;">Show PHP Sourcecode</a></p> <div id="preview"></div> JavaScript: function refreshPreview(inputField,outputField,httpUrl) { var myText = inputField+"="+escape(document.getElementById(inputField).value); if(window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else if(window.ActiveXObject) { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } else { return false; } xmlhttp.open("POST", httpUrl, true); xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xmlhttp.setRequestHeader("Content-length",myText.length); xmlhttp.setRequestHeader("Connection","close"); xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState == 4) { document.getElementById(outputField).innerHTML = xmlhttp.responseText; } } xmlhttp.send(myText); }
Example 3: Check Remote Downloads
Often you provide your clients several mirrors for file downloads. But checking if the files are available at the given loccation before sending the document to the client often includes a huge delay. So you can easily check that after the page has been sent to the client.
The Sandbox
As I mentioned in the introduction, there is one thing you have to worry about here: the so-called sandbox. So you additionally need a simple proxy script (I used PHP as an example).
CSS: .notfound { background-color: #f00; } HTML Body: <ul> <li><a id="link1" href="http://bazzinet.info/index.html" onmouseover="checkLink('link1');">Index</a></li> <li><a id="link2" href="http://bazzinet.info/somerandomfile.html" onmouseover="checkLink('link2');">404</a></li> </ul> JavaScript: function checkLink(myElement) { if(window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else if(window.ActiveXObject) { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } else { return false; } xmlhttp.open("GET", "http://bazzinet.info/tutorials/js-request/proxy.php?url=" + escape(getElementById(myElement).href), true); xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState == 4) { if (xmlhttp.responseText == "404") { getElementById(myElement).className = "notfound"; } } } xmlhttp.send(null); } PHP: // example for HTTP connections. $url = urldecode($_GET['url']); $urldata = parse_url($url); if(!isset($urldata['port'])) { $urldata['port'] = 80; } if(!isset($urldata['query'])) { $urldata['query'] = ""; } else { $urldata['query'] = "?".$urldata['query']; } $errno = 0; $errstr = ""; $fp = fsockopen($urldata['host'],$urldata['port'], $errno, $errstr, 2); if(!$fp) { die(); } $out = "HEAD ".$urldata['path'].$urldata['query']." HTTP/1.0\r\n"; $out .= "Host: ".$urldata['host'].":".$urldata['port']."\r\n"; $out .= "Connection: Close\r\n\r\n"; fwrite($fp, $out); while (!feof($fp)) { $response .= fgets($fp, 1024); } fclose($fp); if (preg_match("#^HTTP/[^\s]*\s(.*?)\s#", $response, $status)) { $code = $status[1]; } echo $code;This is of course a minimalist example without much functionality, feel free to extend it in order to fit your purposes!
A Final Warning
Please be warned to only use JavaScript for unimportant things. Remember, JavaScript can be easily turned off by the client. You have to make sure that your content is accessible without JavaScript!
-
Views(3467) | Comments(0) |
In:
网页前端技术
|
(08/24)
Prototype.js的分析
