如何为所有AJAX链接编写一个jquery函数
我在Windows上使用zend框架。 我想第一次在我的项目中实现ajax。 我搜索了帮助并创建了一个非常简单的ajaxfunction。
IndexController.php
public function indexAction() { } public function oneAction() { } public function twoAction() { }
index.phtml
One Two
one.phtml content comes here two.phtml content comes here
AJAX.js
jQuery(document).ready(function(){ jQuery('.one').click(loadOne); jQuery('.two').click(loadTwo); }); function loadOne(event) { event.preventDefault(); jQuery.ajax({ url: '/index/one', success: function( data ) { jQuery('#one').html(data); } }); } function loadTwo(event) { event.preventDefault(); jQuery.ajax({ url: '/index/two', success: function( data ){ jQuery('#two').html(data); } }); }
上面的代码工作,并在单击其链接时分别在“一个”和“两个”DIV中加载one.phtml和two.phtml的数据。 您可以看到我必须为每个链接创建单独的jquery函数,并且还必须为每个链接标记添加新类。
我想做的事 ? :
我想对所有AJAX请求只使用一个jquery函数,并且不想在该函数中硬编码url和success属性。
当我将“AJAX”类添加到任何链接标记时,它应该使用AJAX加载内容。
谢谢。
为了简单地加载div中的数据,我会使用load方法
HTML
One Two
one.phtml content comes here two.phtml content comes here
JS
jQuery(document).ready(function(){ jQuery('.ajax').click(function(event){ event.preventDefault(); var target = '#' + jQuery(this).attr('rel'); var href = jQuery(this).attr('href'); jQuery( target ).load( href ); }); });
使用单个类来标识应使用ajax调用而不是正常使用的所有链接。 并将rel
属性添加到将包含容器div的id
的链接。
简单又好看。 不需要Jquery。 看看这个: Bjax
用法:
最后,在你的html的HEAD中包含这个:
$('a').bjax();
有关更多设置,请在此处结帐演示: Bjax Demo
也许这个:
function loadData(url, callback) { jQuery.ajax({url: url, success: callback}); } loadData('/index/one', function( data ) { jQuery('#one').html(data); }) loadData('/index/two', function( data ) { jQuery('#two').html(data); })
为了使其更加紧凑,您可以为两者定义相同的回调,然后让处理程序决定应该将响应数据写入哪个元素。
紧凑版:
$(函数(){ $( '一个')点击(loadOne); $( '两个')点击(loadTwo); }); function loadOne(event){ event.preventDefault(); $( '#一个')。 load('/ index / one') ; } function loadTwo(event){ event.preventDefault(); $( '#两个')。 load('/ index / two') ; }