I'm thinking of a way to reduce the amount of javascript code by enabling ajax on links from attributes. Example:
我正在考虑一种方法,通过从属性中启用ajax来减少javascript代码的数量。例子:
<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
.
async="true"将禁用链接(href)的默认行为,并使用数据端点值进行ajax调用,并将其插入到rel中定义的元素id中。
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).
我不是JS专家,所以我很欣赏使用这种方法的任何想法和缺陷。诸如缓存:true等选项将会很酷,但也不需要,因为我希望这样做可以获得包含更多或更少的实时数据的部分视图(不需要缓存)。
(This 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)
(这是我在facebook上看到的关于如何最小化他们的代码的演讲中得到的启发,但与他们如何优化每一个字节相比,这可能非常简单)
1 个解决方案
#1
9
Something like this
像这样的东西
Html
Html
<a href="/Default/Link.html"
data-endpoint="/Ajax/Link.html"
data-target="targetId"
data-cache="false",
data-async="true">Click me!</a>
jQuery
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 );
}
}
});
});
#1
9
Something like this
像这样的东西
Html
Html
<a href="/Default/Link.html"
data-endpoint="/Ajax/Link.html"
data-target="targetId"
data-cache="false",
data-async="true">Click me!</a>
jQuery
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 );
}
}
});
});