0

我打算使用此代码http://gist.github.com/110410转储 Prototype 以支持 jQuery,但我确实遇到了问题。

这是我的 HTML(一个 link_to 生成的链接):

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

问题:

除了页面重新加载之外,一切都正常工作。我怀疑提交通过导致页面重新加载。

有没有一种优雅的方法来防止这种情况?返回假;在这种情况下似乎没有削减它。

4

1 回答 1

0

嗯。使用这个(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>

我将真实性令牌放在锚的 rel attr 中,假设令牌对产品是唯一的。


更新

因为显然 Rails 根本无法控制任何事情:

<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>
于 2010-04-21T12:52:55.807 回答