【问题标题】:Auto ajax selectors with Jquery使用 Jquery 的自动 ajax 选择器
【发布时间】:2010-10-11 16:00:11
【问题描述】:

我正在尝试制作一个概念验证网站,但我想要完美的退化。因此,我将首先用纯 XHTML 编写网站代码,然后添加类和 id 以将它们挂接到 jQuery 中。

我想做的一件事是最终为我的所有链接启用 Ajax xmlhttprequest,以便它们显示在视口 div 中。我希望这个视口成为来自多个外部页面的任何 xmlhttprequest 的“通用”转储。

我想知道我是否能够硬编码如下内容:

<a href="blah.html" class="ajax">, <a href="bleat.html" class="ajax">

等等。如您所见,我使用类 ajax 给出了我想调用 Ajax 请求的所有链接标签。在我基于 jQuery 的 JS 中,我希望能够对其进行编码,以便所有积极的 ${"a").filter(".ajax") 将自动加载它们各自的 href [variable] 作为 ajax 请求。

请帮忙。我是n00b。

【问题讨论】:

    标签: css ajax jquery xmlhttprequest css-selectors


    【解决方案1】:

    通过您的示例,您应该能够做到:

    $('.ajax').click(function () { 
        // Your code here. You should be able to get the href variable and
        // do your ajax request based on it. Something like:
        var url = $(this).attr('href');
        $.ajax({
            type: "GET",
            url: url
        });
        return false; // You need to return false so the link
                      // doesn't actually fire.
    });
    

    我建议使用与“ajax”不同的类,因为它使代码读起来有点奇怪,因为$('.ajax') 可能被误读为$.ajax()

    $('.ajax').click() 部分为页面上的每个元素注册了一个 onClick 事件处理程序,其中的“ajax”类正是您想要的。然后你使用$(this).attr('href') 来获取点击的特定链接的href,然后做任何你需要的事情!

    【讨论】:

      【解决方案2】:

      类似:

      function callback(responseText){
          //load the returned html into a dom object and get the contents of #content
          var html = $('#content',responseText)[0].innerHTML;
          //assign it to the #content div
          $('#content').html(html);
      }
      
      $('a.ajax').click(function(){
          $.get(this.href, callback);
          return false;
      });
      

      您需要解析#content div 之外的所有内容,以便导航不会显示多次。我正在考虑一个正则表达式,但可能更容易使用 jQuery 来完成,所以我更新了示例。

      【讨论】:

        猜你喜欢
        • 2013-12-13
        • 2022-08-18
        • 2012-06-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多