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 URLtarget
: One HTML element ID. Will be updated with theresponseText
content. SeeparseHTML
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
orvar params = {'name': 'John Doe', 'age': 27}
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 falsehttp
: The used XMLHttpRequest objectxtra
: Thextra
attribute specified in ajax.js
xtra
: An argument that will be passed tocallback
function.filter
: Function that will receive every param you're sending.onload
: Function. Executed whenonreadystatechange
changes to 4.onrequest
: Function. Executed when the request starts.
ajax.post(args)
- Works like
ajax.request
but you don't need to provide themethod
attribute. ajax.get(args)
- Works like
ajax.request
but you don't need to provide themethod
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 theresponseText
attribute. This can be a problem when you set element's methods.
The line that sets<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>
innerHTML
completely killsonclick
event. A workaround for this problem is creating a temporary element and settinginnerHTML
. 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>