如何为所有AJAX链接编写一个jquery函数

Nav*_*eed 4 javascript ajax jquery json zend-framework

我在windows上使用zend框架.我想第一次在我的项目中实现ajax.我搜索了帮助并创建了一个非常简单的ajax功能.

IndexController.php

public function indexAction() {
}

public function oneAction() {
}

public function twoAction() {
}
Run Code Online (Sandbox Code Playgroud)

index.phtml

<script type="text/javascript" src="js/jquery-1.4.2.js"></script>
<script type="text/javascript" src="js/AJAX.js"></script>

<a href='http://practice.dev/index/one' class='one'>One</a>
<a href='http://practice.dev/index/two' class='two'>Two</a>
<br /><br />
<div id="one">one.phtml content comes here</div>
<div id="two">two.phtml content comes here</div>
Run Code Online (Sandbox Code Playgroud)

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);
                    }
    });
}
Run Code Online (Sandbox Code Playgroud)

上面的代码正在处理并在单击其链接时分别在"一个"和"两个"DIV中加载one.phtml和two.phtml的数据.您可以看到我必须为每个链接创建单独的jquery函数,并且还必须为每个链接标记添加新类.

我想做的事 ?:

我想对所有AJAX请求只使用一个jquery函数,并且不希望在该函数中硬编码urlsuccess属性.

当我将"AJAX"类添加到任何链接标记时,它应该使用AJAX加载内容.

谢谢.

Gab*_*oli 8

为了在div中简单加载数据,我将使用load方法

HTML

<script type="text/javascript" src="js/jquery-1.4.2.js"></script>
<script type="text/javascript" src="js/AJAX.js"></script>

<a href='http://practice.dev/index/one' class='ajax' rel="one">One</a>
<a href='http://practice.dev/index/two' class='ajax' rel="two">Two</a>
<br /><br />
<div id="one">one.phtml content comes here</div>
<div id="two">two.phtml content comes here</div>
Run Code Online (Sandbox Code Playgroud)

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

      });
});
Run Code Online (Sandbox Code Playgroud)

使用单个类来标识应使用ajax调用而不是正常使用的所有链接.并将rel属性添加到将包含id容器div的链接.