how to bind the return html data?
In django views I return
context['foo'] = 'bar'
return render_to_response('test.html', context_instance=context)
test.html is included by main.html
On ajax success I am attaching the test.html data into the div having id foobar of the main.html I want to attach the {{ foo }} variable with the main.html too.
success:functi开发者_JS百科on(data) {
$('#foobar').html(data);
}
It attached the data with the foobar element
of a template. There are some variable with the data I want to bind this it to original template. How should I bind those data with the original templates?
Basically you can do that like that:
var context = {
foo: {
id: 1
}
};
$.get("template.html", function(result) {
result = $(result);
$("*", result).each(function() {
var field = $(this).data("field");
if (field) { // Is tag has "data-field" attribute?
//Well, loop on context to find result.
//e.g. result = context["foo"]["id"]
var regExp = /([^.]+)/gi,
o = context,
match;
while (match = regExp.exec(field)) {
var key = match[1];
o = o[key];
}
$(this).text(o);
}
});
$("body").append(result);
});
Template.html:
<div data-field="foo.ID"></div>
The second option's if you got more complex field names, you may wanna use Pure.
精彩评论