How to code one jquery function for all AJAX links

前端 未结 4 957
生来不讨喜
生来不讨喜 2020-12-11 08:25

I am using zend framework on windows. I want to implement ajax in my project first time. I searched for help and created a very simple ajax functionality.

In

相关标签:
4条回答
  • 2020-12-11 08:52

    Compact version:

    $(function(){
        $('.one').click(loadOne);
        $('.two').click(loadTwo);
    });
    
    function loadOne(event) {
        event.preventDefault();
        $('#one').load('/index/one');
    }
    
    function loadTwo(event) {
        event.preventDefault();
        $('#two').load('/index/two');
    }
    0 讨论(0)
  • 2020-12-11 09:01

    Simple and Nice. No Jquery required. Check this out: Bjax

    Usage:

    <script src="bjax.min.js" type="text/javascript"></script>
    <link href="bjax.min.css" rel="stylesheet" type="text/css" />
    

    Finally, include this in the HEAD of your html:

    $('a').bjax();
    

    For more settings, checkout demo here: Bjax Demo

    0 讨论(0)
  • 2020-12-11 09:13

    Maybe this:

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

    To make this even more compact you could define the same callback for both and then have the handler decide which element the response data should be written to.

    0 讨论(0)
  • 2020-12-11 09:16

    for simple loading of data in divs i would use the load method

    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>
    

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

    Use a single class to identify all links that should use ajax calls instead of their normal use. And add a rel attribute to those links that will contain the id of the container div..

    0 讨论(0)
提交回复
热议问题