简体   繁体   中英

jquery for ruby on rails

I am tying to use this code http://gist.github.com/110410 to dump Prototype in favor of jQuery but I do have a problem.

This is my HTML (a link_to generated link):

<a onclick="var f = document.createElement('form'); f.style.display = 'none'; this.parentNode.appendChild(f); f.method = 'POST'; f.action = this.href;var s = document.createElement('input'); s.setAttribute('type', 'hidden'); s.setAttribute('name', 'authenticity_token'); s.setAttribute('value', 'Mi6RcR6YDyvg2uNwGrpbeIJutSHa2fYboU37wSDE7AU='); f.appendChild(s);f.submit();return false;" class="post add_to_cart " href="/line_items?product_id=547">Add to cart</a>

Issue:

Everything works as it should except that the page does a reload. I suspect that the submit gets thru which causes a page reload.

Is there an elegant way to prevent that ? return false; doesn't seem to cut it in this case.

ew. Use this (jQuery):

<a class="post add_to_cart" rel="Mi6RcR6YDyvg2uNwGrpbeIJutSHa2fYboU37wSDE7AU=" href="/line_items?product_id=547">Add to cart</a>
<script>
    $("a.add_to_cart").click(function(){
        $.post(this.href,{'authenticity_token':$(this).attr("rel")});
        return false;
    });
</script>

I put the authenticity token in the rel attr for the anchor assuming the token is unique to the product.


UPDATE

Because apparently Rails gives you no control of anything at all:

<a class="post add_to_cart" href="/line_items?product_id=547" onclick='            $.post(this.href,{"authenticity_token":"Mi6RcR6YDyvg2uNwGrpbeIJutSHa2fYboU37wSDE7AU="});return false;'>Add to cart</a>

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