jQuery和数据属性来处理所有的Ajax调用? [英] jQuery and data-attributes to handle all ajax calls?

查看:99
本文介绍了jQuery和数据属性来处理所有的Ajax调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在想办法通过实现AJAX从属性链接,以减少JavaScript的code量。例如:

 < A HREF =/默认/ Link.html数据终端=/阿贾克斯/ Link.html相对=目标ID异步=真>点击ME<!/ a取代;
 

异步=真正的将禁止链接(的href )的默认行为,并做一个Ajax调用使用数据端点值,并将其插入到相对中定义的元素的ID。

我不是JS专家,所以我最好的AP preciate使用这种方法的任何想法或陷阱。像高速缓存选项:真等将是很酷,以便能够传递为好,但不是真的需要,我想这样做是为了获得一个包含更多或更少的实时数据(没有缓存需要)的部分景色。

(这是从一个演讲中,我看到了在facebook上分享了如何最小化其code的启发,但可能是非常简单的比较,他们怎么优化都记录下来,以每一位'N字节)

解决方案

像这样

HTML

 < A HREF =/默认/ Link.html
    数据端点=/阿贾克斯/ Link.html
    数据目标=目标ID
    数据缓存=假,
    数据异步=真>点击我<!/ a取代;
 

的jQuery

  $('A [数据异步=真])。点击(函数(五){
    即preventDefault();
    VAR自我= $(本),
        URL = self.data这样('端点'),
        目标= self.data这样的(目标),
        缓存= self.data这样的(高速缓存);

    $阿贾克斯({
        网址:网址,
        缓存:缓存,
        成功:功能(数据){
                       如果(目标!==未定义){
                          $('#'+目标)。html的(数据);
                       }
                 }
    });
});
 

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)

解决方案

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

这篇关于jQuery和数据属性来处理所有的Ajax调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆