jQuery and data-attributes to handle all ajax calls?

一世执手 提交于 2019-12-18 04:16:36

问题


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).

(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)


回答1:


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 );
                       }
                 }
    });
});


来源:https://stackoverflow.com/questions/6908592/jquery-and-data-attributes-to-handle-all-ajax-calls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!