AJAX - The Complete Reference

(avery) #1

PART II


Chapter 5: Developing an Ajax Library 203


However, it is not necessary to download and set up YUI files both for testing and
production, as Yahoo has decided to make its files available in a minimized delivery-ready
form on its own servers. Use these versions directly to avoid versioning and delivery concerns.

<script src="http://yui.yahooapis.com/2.3.0/build/yahoo/yahoo-min.js"></script>
<script src="http://yui.yahooapis.com/2.3.0/build/event/event-min.js"></script>
<script src="http://yui.yahooapis.com/2.3.0/build/connection/connection-min.js">
</script>

NNOT EOTE The provided YUI files are “minified” with white space and comments removed. While this is
obviously great for delivery, you will find inspecting the code to be tedious so you may want to
also download the entire package for reference.

YUI Request Syntax
The first method in the Connection Manager library we use is asyncRequest(), which
creates an asynchronous request using an XHR object. The following syntax should look
familiar, since it simply wraps an XHR:

YAHOO.util.Connect.asyncRequest(method, URL, callback, postData)

The properties passed are as follows:


  • method A string indicating the type of HTTP method to use (for example, GET,
    POST, HEAD, and so on)

  • URL A string containing the URL to invoke including any query string data

    • callback A user-defined object indicating functions and values to use for request
      or error callback



  • postData An x-www-form-urlencoded payload string; the parameter is only
    required if the method is set to POST


The method returns a connection object that contains a unique transaction identification
property (tId). Saving the return object is useful if you’re planning on monitoring or
controlling the request later on.

var connection = YAHOO.util.Connect.asyncRequest("GET",
"http://ajaxref.com/ch1/sayhello.php", callback)

The callback object bears some discussion as it has a number of members. The first is
success, which is a function to be called upon a successful response.

var callback = { success: function (response) { /* handleResponse */ } };

More likely these would be defined separately, like so:

function handleResponse(response) { /* handle response */ }
var callback = { success: handleResponse };
Free download pdf