如何防止两次发送ajax调用

时间:2018-03-18 04:00:48

标签: javascript jquery ruby-on-rails ajax coffeescript

我在地图上有很多弹出窗口,需要进行销毁操作。我附加了事件处理程序来发送ajax调用来销毁操作。但它只需单击就会发送两个ajax调用,下面是我的代码

   $(document).on 'click', '#map .leaflet-popup-content #delete', ->
     if confirm('Are you sure?')
       $.ajax
        type: 'POST'
        url: 'incidents/' + incident_id
        dataType: 'script'
        data:
          _method: 'delete'
          id: incident_id
        success: ->
          successFunction

1 个答案:

答案 0 :(得分:2)

您需要在您的函数中添加event作为输入,然后在event .preventDefault() method上调用

$(document).on('click', function(event, '#map .leaflet-popup-content #delete'){
     event.preventDeafault();
     // your code
});

我真的不知道如何用coffeescript写它,也许是这样的?

 $(document).on 'click', '#map .leaflet-popup-content #delete', (event) ->
     event.preventDefault()
     if confirm('Are you sure?')
       $.ajax
        type: 'POST'
        url: 'incidents/' + incident_id
        dataType: 'script'
        data:
          _method: 'delete'
          id: incident_id
        success: ->
          successFunction