开发者

Call prototype(javascript) function on link click?

I am working with AJAX with prototype and PHP. It is working for me but I need some small changes. Following is my running code for AJAX request:

JS/Prototype:

function ajaxRequest(url) {

    new Ajax.Request( url, {

          method: 'get',
          onSuccess: function( transport ) {

            // get json response
            var json = transport.responseText.evalJSON( true );
            alert(json);
        },     
        onFailure: function() {             
            alert('Error with AJAX request.'); 
        }  
    });

  开发者_如何学Python  return false;
}

HTML:

<a href='javascript:ajaxRequest("/testajax/ajaxresponse");'>Testing AJAX</a>

Question:

Now I want to change my link like this:

<a href='/testajax/ajaxresponse' class='AjaxLink'>Testing AJAX</a>

So prototype function should capture click event of class='AjaxLink' links and then get href part of clicked link and proceed. How can I change my above prototype function for such kind of links.

Thanks


If you have Prototype 1.7 then this way is available:

document.on('click', 'a.AjaxLink', ajaxRequest.curry('/testajax/ajaxresponse'));

Otherwise you'll have to rely on good old Event.observe:

$$('a.AjaxLink').invoke('observe', 'click', 
    ajaxRequest.curry('/testajax/ajaxresponse'));

Just re-read the question and I see you want to use the href attribute. Jan Pfiefer was very close.

document.on('click', 'a.AjaxLink', function(event, element) {
    return ajaxRequest(element.href);
});


This wont work. Why do you want such a link? If a link is specified in this way any click on it will follow its href and change location of actual document. Only way to prevent such a behavior then is by adding onclick again or in $(document).ready bind onclick handler, and manualy cancel the event.

UPDATE However to bind onclick event on all links with AjaxLink class,execute request and cancel the event:

$(document).ready(function(){
   $('.AjaxLink').click(
      function(e){
        ajaxRequest(this.href);
        event.preventDefault ? event.preventDefault() : event.returnValue = false;
      }
   ); 
});


This will work:

$$('a.AjaxLink').each(function(element) {
    element.observe('click', function(e) {
        var element = e.element()
        Event.stop(e)          
        alert(element.href)
    });
})
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜