I'm thinking of a way to reduce the amount of javascript code by enabling ajax on links from attributes. Example:
<a href="/Default/Link.html" data-endpoint="/Ajax/Link.html" rel="targetId" async="true">Click me!</a>
async="true"
will disable default behaviour of the link (href
), and do a ajax call using the data-endpoint
value and insert it to the element id defined in rel
.
I'm no JS expert, so I'd appreciate any thoughts or pitfalls using this approach. Options like cache: true etc would be cool to be able to pass in as well, but not really needed as I'd like to do this to get partial views that contains more or less live data ( no cache needed).
(Thi开发者_如何转开发s is inspired from a talk i saw on how facebook minimized their code, but probably very simplified compared to how they optimize everything down to every bit 'n byte)
Something like this
Html
<a href="/Default/Link.html"
data-endpoint="/Ajax/Link.html"
data-target="targetId"
data-cache="false",
data-async="true">Click me!</a>
jQuery
$('a[data-async="true"]').click(function(e){
e.preventDefault();
var self = $(this),
url = self.data('endpoint'),
target = self.data('target'),
cache = self.data('cache');
$.ajax({
url: url,
cache : cache,
success: function(data){
if (target !== 'undefined'){
$('#'+target).html( data );
}
}
});
});
精彩评论