jQuery and data-attributes to handle all ajax calls?

前端 未结 1 1354
慢半拍i
慢半拍i 2020-12-17 01:57

I\'m thinking of a way to reduce the amount of javascript code by enabling ajax on links from attributes. Example:



        
相关标签:
1条回答
  • 2020-12-17 02:09

    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 );
                           }
                     }
        });
    });
    
    0 讨论(0)
提交回复
热议问题