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
argsis 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 theresponseTextcontent. SeeparseHTMLmethod.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: Thextraattribute specified in ajax.js
xtra: An argument that will be passed tocallbackfunction.filter: Function that will receive every param you're sending.onload: Function. Executed whenonreadystatechangechanges to 4.onrequest: Function. Executed when the request starts.
ajax.post(args)- Works like
ajax.requestbut you don't need to provide themethodattribute. ajax.get(args)- Works like
ajax.requestbut you don't need to provide themethodattribute. 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
innerHTMLwith theresponseTextattribute. 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>innerHTMLcompletely killsonclickevent. 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>