【问题标题】:How to send ajax request in rails app without using remote如何在不使用远程的情况下在 Rails 应用程序中发送 ajax 请求
【发布时间】:2013-12-23 12:31:29
【问题描述】:

这很好用

<%#= link_to t('.add_html'), 'javascript:void(0);', :class => "line-item", :product => product.id %>

$('document').ready(function(){
        $(".line-item").click(function(){
            var prod = $(this).attr('product');
            $.ajax({
                url:'<%#= line_items_url %>',
                data: {product_id: prod},
                type: 'POST',
                dataType: 'script'
            });
        });
    });

但是当我使用按钮时没有任何反应。请让我知道我在这里缺少什么?

<%= button_to t('.add_html'), 'javascript:void(0);', :class => "line-item", :product => product.id %>

【问题讨论】:

标签: ruby-on-rails ajax erb


【解决方案1】:

:remote =&gt; :true 只是创建一个ajax请求;你可以做你自己的ajax请求没问题:

$("button").on("click", function(){
    $.ajax({
        url: $(this).attr("href");
        success: function(data) { //handle returned data },
        error: function(data)   { //handle errors }
    });
});

我认为您在问一个不同的问题(如何让您的电话正常工作),如果您愿意,我可以更新答案以反映

【讨论】:

  • 我应该在 attr("href"); 中使用 href或者我应该使用那里的链接?
  • 你可以使用链接!唯一的问题是我认为您的语法不正确;但你实际上只是把你的链接放在那里。你如何得到它无关紧要
  • 链接可以正常工作,但按钮不能正常工作。请立即检查问题
  • 好的,你必须记住button_to basically creates a form,所以你必须做类似url: $(this).parent().attr("action");的事情
【解决方案2】:

你需要防止默认:

$(document).ready(function(){
    $("button").click(function(ev){
        $.post(this.url); // I'm not sure this is correct
        ev.preventDefault();
    });
});

【讨论】:

  • 链接可以正常工作,但按钮不能正常工作。请立即检查问题
  • 为什么必须使用 button_to 助手?
猜你喜欢
  • 2017-06-05
  • 2017-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-11
相关资源
最近更新 更多