Habiendo visto un poco cómo es que se maneja Ajax, veamos las facilidades que proporciona prototype. Prototype es un framework que sirve para hacer la programación en javascript un poco menos trabajosa, ya que permite al programador abstraerse de las diferencias sutiles de los diferentes navegadores.
Para empezar, prototype posee muchas funciones, pero nosotros nos vamos a centrar en la parte de Ajax. Una de las funciones interesantes que tiene es, $(“identificador”), la cual retorna el objeto dentro del documento html, también agrega funcionalidad a javascript para crear clases.
Prototype para el manejo de Ajax, posee las clases:
Ajax.Request, su constructor recibe una URL y un conjunto de opciones.
new Ajax.Request(«hello.php», {
onSuccess : function(resp) {
alert(«The response from the server is: » + resp.responseText);
},
onFailure : function(resp) {
alert(«Oops, there’s been an error.»);
},
parameters : «name=Fred»
});
Lista completa de las opciones permitidas
Propiedad
Tipo
Default
Descripción
method
String
‘post’
Method of the HTTP request
parameters
String
‘’
The url-formatted list of values passed to the request
asynchronous
Bolean
true
Indicates if the AJAX call will be made asynchronously
postBody
String
undefined
Content passed to in the request’s body in case of a HTTP POST
requestHeaders
Array
Undefined
List of HTTP headers to be passed with the request. This list must have an even number of items, any odd item is the name of a custom header, and the following even item is the string value of that header. Example:[‘my-header1’, ‘this is the value’, ‘my-other-header’, ‘another value’]
onXXXXXXXX
Function(XMLHttpRequest, Object)
Undefined
Custom function to be called when the respective event/status is reached during the AJAX call. Example var myOpts = {onComplete: showResponse, onLoaded: registerLoaded};. The function used will receive one argument, containing the XMLHttpRequest object that is carrying the AJAX operation and another argument containing the evaluated X-JSON response HTTP header.
onSuccess
Function(XMLHttpRequest, Object)
undefined
Custom function to be called when the AJAX call completes successfully. The function used will receive one argument, containing the XMLHttpRequest object that is carrying the AJAX operation and another argument containing the evaluated X-JSON response HTTP header.
onFailure
Function(XMLHttpRequest, Object)
undefined
Custom function to be called when the AJAX call completes with error. The function used will receive one argument, containing the XMLHttpRequest object that is carrying the AJAX operation and another argument containing the evaluated X-JSON response HTTP header.
onException
Function(Ajax.Request, exception)
undefined
Custom function to be called when an exceptional condition happens on the client side of the AJAX call, like an invalid response or invalid arguments. The function used will receive two arguments, containing the Ajax.Request object that wraps the AJAX operation and the exception object.
insertion
an Insertion class
undefined
A class that will determine how the new content will be inserted. It can be Insertion.Before, Insertion.Top, Insertion.Bottom, or Insertion.After. Applies only to Ajax.Updater objects.
evalScripts
Boolean
undefined, false
Determines if script blocks will be evaluated when the response arrives. Applies only to Ajax.Updater objects.
decay
Number
undefined, 1
Determines the progressive slowdown in a Ajax.PeriodicalUpdater object refresh rate when the received response is the same as the last one. For example, if you use 2, after one of the refreshes produces the same result as the previous one, the object will wait twice as much time for the next refresh. If it repeats again, the object will wait four times as much, and so on. Leave it undefined or use 1 to avoid the slowdown.
frequency
Number
undefined, 2
Interval (not frequency) between refreshes, in seconds. Applies only to Ajax.PeriodicalUpdater objects.
* fuente: http://www.sergiopereira.com/articles/prototype.js.html, además posee una explicación más detalladas de todas las clases que posee prototype.
Las más importantes son: method (que indica el método por el cual se va a hacer una consulta al servidor), parameters (los parámetros que va a recibir, un string con formato URL), onSucces (que es la función que se va a realizar cuando se reciba una respuesta satisfactoria), onFailure (una función que se realiza en caso de que en la petición se produzca un error).
Pero, normalmente, Ajax es usado simplemente para actualizar el contenido de elementos HTML. Prototype tiene otra clase, Ajax.Updater que usa Ajax.Request internamente para hacer el proceso aún más sencillo.
Ajax.Updater, Además de la URL, Ajax.Updater recibe la id del elemento HTML cuyo contenido reemplazar por la respuesta del servidor.
new Ajax.Updater(«mydiv», «hello.php», {
parameters : «name=Fred»,
onFailure : function(resp) {
alert(«Oops, there’s been an error.»);
}
});
Ajax.PeriodicalUpdater similar, pero hace la llamada de Ajax repetidamente en un intervalo que usted asigna:
new Ajax.PeriodicalUpdater(«mydiv», «hello.php», {
// initial number of seconds interval between calls
frequency : 1,
decay : 2
});
La opción decay le permite dar a su servidor un poco de soltura si se devuelven muchas respuestas idénticas. Esencialmente, PeriodicalUpdater siempre hace una petición que compara los resultados con lo que el servidor devolvió la vez anterior. Si los valores son los mismos, se multiplica el intervalo por el valor de decay. De esta manera, para el ejemplo antedicho, se haría la siguiente petición dos segundos después, cuatro segundos después, etcétera, hasta que se recibiera un resultado diferente del servidor. En aquel punto, el intervalo sería reinicializado a un segundo.