Using XMLHttpRequest
function readyAJAX() { try { return new XMLHttpRequest(); } catch (e) { try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) { return "New Browser Required."; } } } }
Sending an AJAX Request
var requestObj = readyAJAX(); var url = "http://www.amazon.com"; requestObj.open("GET", url, true) ; // asynchronous non-blocking request // Actual send with this line requestObj.send();
Processing an AJAX Response
// a synchronous call and response retrieval
var requestObj = readyAJAX();
var url = "http://www.amazon.com";
requestObj.open("GET", url, false);
requestObj.send();
if (requestObj.status == 200) {
alert(requestObj.responseText);
} else {
alert(requestObj.statusText);
}
// an Asynchronous call and response retrieval var requestObj = readyAJAX(); var url = "http://www.amazon.com"; requestObj.open("GET", url, true); requestObj.send(); // Use onreadystatechange to trigger code // that checks the event's readyState // readyState : 0 - uninitialized, open but yet has to be called // 1 - open but yet to be sent // 2 - sent // 3 - receiving, the response has yet to be ready // 4 - loaded, response fully received requestObj.onreadystatechange = function () { if (requestObj.readyState == 4) { if (requestObj.status == 200) { alert(requestObj.responseText); } else { alert(requestObj.statusText); } } }
Processing an XML Response
var requestObj = readyAJAX(); var url = "http://www.amazon.com"; requestObj.open("GET", url, false); requestObj.send(); if (requestObj.status == 200) { var xmldocument = requestObj.responseXML; alert(xmldocument.getElementsByTagName("isbn")[0].childNodes[0].nodeValue); } else { alert(requestObj.statusText); }
Processing an JSON Response
var requestObj = readyAJAX(); var url = "http://www.amazon.com"; requestObj.open("GET", url, false); requestObj.send(); if (requestObj.status == 200) { var jsondocument = eval('(' + requestObj.responseText + ')'); alert(jsondocument.book.title); } else { alert(requestObj.statusText); } // JSON data looks like this: { "book": { "title": "bookname", "isbn" : "938874637383" } }
Processing Headers
- HTTP HEAD method returns just the response headers from the server.
- GET method returns the headers and the body
- Useful to determine whether a resource has been updated or changed.
- Useful header: Expires, indicating the client should request a refreshed copy from server.
- Use "getAllResponseHeaders()" method of "XMLHttpRequest" object to obtain only the response headers
- requestObj.getAllResponseHeaders();
<script type = "text/javascript"> function readyAJAX() { ... } var requestObj = readyAJAX(); var url = "http: //www.domain.com/"; requestObj.open ("HEAD", url, true); requestObj.send(); requestObj.onreadystatechange = function () { if (requestObj.readyState == 4) { if (requestObj.status == 200) { alert (requestObj.getAllResponseHeaders()); } else { alert (requestObj.statusText); } } } </script>
Using POST method
- Parameters sent with POST request are contained int he body of the request rather than in the URL, as in GET request
- Less likely to be seen by those trying to find ways into your application.
- Supports larger requests.
- Amount or size of a GET request are often limited by some servers to a certain amount of characters.
- Amount or size of a POST request can be limited as well but are almost always much greater.
- Requires an additional header to be set within the request, using "setRequestHeader()" method.
- requestObj.setRequestHeader (header, value);
// AJAX requests using GET // The URL looks like: // http://www.domain.com/books/javascriptsbs/isbn.php?isbn=9876543212345 //AJAX request using POST requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); // Example <script type = "text/javascript"> function readyAJAX() { ... } var requestObj = readyAJAX(); var url = "http://www.domain.com/books/javascriptsbs/post.php"; var params = "num1=2&num2=2"; requestObj.open("POST", url, true); requestObj.setRequestHeader ("Content-type", "application/x-www-form-urlencoded"); requestObj.send(params); requestObj.onreadystatechange = function () { if (requestObj.readyState == 4) { if (requestObj.status == 200) { alert (requestObj.responseText); } else { alert (requestObj.statusText); } } } </script>
AJAX and jQuery
- List of Parameters
- type
- url
- dataType
- success
- error
- timeout
- data (to the server) :
- data: (key1=value1 & key2=value2)
- data: {key3=value3, key4=value4}
- Async vs cache
- Functions
- .load()
- .post()
- .get()
- .ajax()
- .getJSON() - same as calling .ajax() with parameter dataType set to 'json'
- using parameter to call GET, POST, or set time-out
- $.ajax ({ parameter: value });
$.ajax ({ url: "testajax.aspx", success: function (data) { alert ("Successful load"); } )}
<script type = "text/javascript"> $(document).ready (function () { $.ajax( { type: "GET", url: "json.php", dataType: "json", success: showStates, error: errorFunction, timeout: 5000, data: "state=CA" }); // The function showStates creates a list and adds it to a form's <SELECT> // drop-down box. function showStates (data, status) { $.each (data, function (item) { $("#states").append ("<div>" + data[item] + "</div>"); } ); } function errorFunction ( xhr, statusMessage, httpErrorCode ) { alert ("An error has occurred: " + statusMessage); } }); </script>
No comments:
Post a Comment