【问题标题】:Cannot get value from list group item for ajax request无法从列表组项中获取 ajax 请求的值
【发布时间】:2020-01-16 02:11:00
【问题描述】:

我尝试了很多解决方案,但仍然无法通过 ajax 请求发送此值。用户可以在下面单击侧导航栏中的链接,我希望将类别名称发送到控制器。

    <div class="mini-submenu">
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
    </div>
    <div class="list-group">
        <span href="#" class="list-group-item active">
            Categories
            <span class="pull-right" id="slide-submenu">
                <i class="fa fa-times"></i>
            </span>
        </span>
        <% Movie.category_types.keys.each do |category| %>
            <a href="#" class="list-group-item">
                <i class="fa fa-folder-open-o"></i> <%= category.capitalize.humanize %> <span class="badge"><%= Movie.find_category_amount(category) %></span>
            </a>
        <% end %>
    </div>  
</div>
<script>
    $(document).ready(function(){  
        $(".list-group-item").on('click',function(e) { 
            $.ajax({
                type: "GET",
                data: $(this).attr('value'),
                url: "<%= movies_path %>",
                dataType : "script",
            }); 
        });
    });
</script>


【问题讨论】:

    标签: jquery ruby-on-rails ruby ajax


    【解决方案1】:

    您可以通过

    获取类别名称
    e.target.childNodes[1].data // to send only the category name, OR
    e.target.innerText // to send the full text inside the dom element
    

    另外,请使用preventDefault()。所以,例如:

    $(".list-group-item").on('click',function(e) { 
        e.preventDefault();
        $.ajax({
          type: "GET",
          data: {category_name: e.target.childNodes[1].data},
          url: "/your_path_here",
          dataType : "script"
        }); 
      }); 
    

    【讨论】:

    • 谢谢。奇怪的是参数中没有传递数据。我什至看不到关键的 category_name。
    • 如果您在点击时执行console.log(e),它会记录事件吗?
    • dataType:'script' 对于这样的用例来说似乎很不寻常
    • 如果你尝试dataType:'json'?就像 charlieftl 提到的那样
    • 不一样。奇怪的是,如果我用'{'example':'test'}'替换数据,它可以工作,我可以在参数中看到它。
    猜你喜欢
    • 2018-03-23
    • 1970-01-01
    • 2017-05-25
    • 1970-01-01
    • 2021-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多