使用Jquery自动ajax选择器
-
03-07-2019 - |
题
我正在尝试制作一个概念验证网站,但我希望完美降级。因此,我将首先使用普通的XHTML对网站进行编码,然后添加类和& ids将它们挂钩在jQuery中。
我想要做的一件事是最终为我的所有链接启用Ajax xmlhttprequest,以便它们显示在视口div中。我希望这个视口是一个“通用”视频。从多个外部页面转储任何xmlhttprequest。
我想知道我是否能够硬编码:
<a href="blah.html" class="ajax">, <a href="bleat.html" class="ajax">
等。正如您所看到的,我使用类ajax给出了我想要调用Ajax请求的所有链接标记。在我的基于jQuery的JS中,我希望能够对其进行编码,使得所有正$ {&quot; a&quot;。)。filter(&quot; .ajax&quot;)将自动加载它们各自的href [variable]作为ajax请求。 / p>
请帮忙。我是n00b。
解决方案
通过您的示例,您应该能够:
$('.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,然后做你需要的任何事情!
其他提示
类似的东西:
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来执行此操作,因此我更新了示例。
不隶属于 StackOverflow