简体   繁体   中英

How can I keep my Ajax call from posting back to the server when using Prototype?

I am trying to keep my Ajax call from posting back to the server when using Prototype .

Code:

echo " <a href='my.php?action=show&amp;id=".$fid."'
onclick=\"return  display('".$fid."');\"> ";  
echo "" .$fname."</a> ";

How can I do this?

Your display() function should return false; to prevent the default link action from happening.

It's pretty easy to do (though I would encourage you to do it unobtrusively via the Event.observe() pattern explained in http://prototypejs.org/api/event ).

Here is a solution that doesn't follow the encouragement I just gave (for the sake of not changing to much of your code and allowing you to easy see what it's doing.).

echo " <a href='my.php?action=show&amp;id=".$fid."'
        onclick=\"Ajax.Request(this.href); return false;\"> ";
echo "" .$fname."</a> ";

What might be better is adding a class to this link, something like 'xhr' and then unobtrusively-finding all links with an xhr class and observe for a click and then fire off the XMLHttpRequest request. Here is how I'd do that.

So in your body, change the link element to:

echo '<a href="my.php?action=show&amp;id=' . $fid .'" class="xhr">' . $fname . '</a> ';

Now somewhere your script area do:

<script type="text/javascript" charset="utf-8">
    ....
    // Wait for the DOM to be loaded (http://prototypejs.org/api/document/observe)
    document.observe('dom:loaded',function(){
       // Use Prototype's $$ utility method to find all the link's
       // with class xhr (http://prototypejs.org/api/utility/dollar-dollar)
       $$('a.xhr').each(function(link_element){
           // Iterate through each of these links and attach the following observer.
           link_element.observe('click', function(click_event){
               Ajax.Request(link_element.href);
               // stop() will cancel the click-event from "doing" anything else
               // http://prototypejs.org/api/event/stop
               click_event.stop();
           });
       });
    });
</script>

What happens now, is after the DOM loads (but before the page is displayed) your click-observer will be attached to all link-elements with the class 'xhr'. It captures the click event, fires off an XMLHttpRequest request, and prevents the event from preforming the default action (in this case following the link to another page) by calling the stop() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM