How to update multiple elements in a MooTools Request.HTML call
Using MooTools Request.HTML, I have my Request call working perfectly, updating my page element by using something like:
onComplete: function() {
var response = this.response.text;
$('content').set("html", response);
}
However, I'd like to be able to have a response have multiple elements that are updated by ID and I can't for the life of me get this working correctly. For instance, if my response is:
<response>
<div id="header"><h1>My Title</h1></div>
<div id="content"><h2>Content</h2><p>This is my content</p></div>
<div id="footer"><p>Special footer for this page</p></div>
</response>
I would like the code to loop through the child elements of <response>, grab the id, match that id to an element in the page, and replace the element innerHTML of the pa开发者_JAVA百科ge with the element innerHTML from the response. It didn't seem to be that hard but I just can't seem to get this working. Any help would be much appreciated. Thanks.
you can walk the returned elements form Request.HTML like so:
http://jsfiddle.net/dimitar/NF2jz/1139/
new Request.HTML({
url: '/echo/html/',
data: {
html: data,
delay: 1
},
method: 'post',
onComplete: function() {
// first, only get elements that have an id and are divs
// this may be slow as it looks for ALL els returned, depends on your
// fragment
var filtered = this.response.elements.filter(function(el) {
return el.get("id") && el.get("tag") == "div";
});
// This wil be even faster, working with your response fragment
// where your els are children of the first node:
// get div els where id is set via Slick
var filtered = this.response.tree[0].getElements("div[id]");
filtered.each(function(el) {
// get the id
var id = el.get("id");
// remove the id from the element so dom selector works correctly
el.set("id", null);
// look for dom element that matches
var target = document.id(id);
// if found, update html
if (target)
target.set("html", el.get("html"));
});
}
}).send();
as Tim Weink from mootools-core likes to point out, I have a nasty habit of using undocumented mootools features that fall outside of the public API, such as accessing this.response
directly where I should use the named arguments instead. Keep it in mind and look at the documentation on which argument will match this.response.elements
or this.response.tree
- in the unlikely event that mootools change their API and make that unavailable.
onSuccess:function(responseJSON, responseText)
{
var data_length = responseJSON.data.length;
for(var i=0;i<data_length;i++){
$(responseJSON.data[i].id).set('html',responseJSON.data[i].html);
}
}
The JSON reposnse from server
{data: [
{id:"header",html:"<h1>My title</h1>"},
{id:"content",html:"<h2>Content</h2><p>This is my content</p>"},
....
]
}
There are some short cutts you can do, but this shows the logic.
精彩评论