Go to English Blog

ajax.js

Leia em 1 minuto

Lightweight AJAX Library.

VIEW SOURCE: ajax.js (4.4kb)
MINIFIED VERSION: ajax_min.js (2kb)

API

ajax.create()
Returns a new XMLHttpRequest object.
ajax.request(args)
Starts a new request. The param args is an object that can receive the following attributes:
  • method: The request method (GET or POST)
  • url: The request URL
  • target: One HTML element ID. Will be updated with the responseText content. See parseHTML method.
  • tries: If the initial request fails, ajax.js will try again until reach this value.
  • params: Params that will be sent to URL. Can be object or string
    var params = {'name': 'John Doe', 'age': 27}
    or
    var params = "name=John Doe&age=27";
  • callback(success, http [, xtra]): Function that will receive the XMLHttpRequest response. Can receive 3 params:
    • success: True if request returns status 200. Otherwise, returns false
    • http: The used XMLHttpRequest object
    • xtra: The xtra attribute specified in ajax.js
  • xtra: An argument that will be passed to callback function.
  • filter: Function that will receive every param you're sending.
  • onload: Function. Executed when onreadystatechange changes to 4.
  • onrequest: Function. Executed when the request starts.
ajax.post(args)
Works like ajax.request but you don't need to provide the method attribute.
ajax.get(args)
Works like ajax.request but you don't need to provide the method attribute.
ajax.parseHTML(target, source [, empty])
target: element ID.
source: HTML code that you want to insert.
empty: If true, removes all children elements.
When you start doing AJAX, one common approach is setting innerHTML with the responseText attribute. This can be a problem when you set element's methods.
<div id="mydiv">
	Click this text
</div>

<script type="text/javascript">
var div = document.getElementById('mydiv');
div.onclick = function()
{
	alert('Wow!');
}
div.innerHTML = 'If you click here nothing will happen';
</script>
The line that sets innerHTML completely kills onclick event. A workaround for this problem is creating a temporary element and setting innerHTML. Then, you can clone every child node and insert in your element.
<div id="mydiv">
	Click this text
</div>

<script type="text/javascript">
var div = document.getElementById('mydiv');
div.onclick = function()
{
	alert('Wow!');
}

var tmp = document.createElement('div');
tmp.innerHTML = "<p>Inserted with innerHTML</p>";

for (var i = 0, clone; clone = tmp.childNodes[i]; i++) {
	div.appendChild(clone);
}
</script>