weixin_33725807 2016-03-14 16:49 采纳率: 0%
浏览 19

不起作用多AJAX代码

Hi I have a problem when I run the code a second code will not run. However when the second code to be executed each time the code still runs. The first code adds value to the database and database re-runs and the second code amount removed from the table, but only the amount that was removed from the environment.

my problem is jQuery does not execute on div loaded with ajax!

How to bind click event on dynamically added element for this code? How to solve this problem??

first code:

<script>
            $('#submit').on('click', function (e) {
                e.preventDefault();
                var data = $('#create').serialize();
                $.ajax({
                    headers: {
                        'X-CSRF-Token': $('input[name="_token"]').val()
                    },
                    type: 'post',
                    url: '{!! URL::route('category') !!}',
                    data: data,
                    success: function (data) {
                        var dataDelete = 'category/' + data.id + '/delete';
                        var dataCat = data.cat;
                        var dataId = data.id;
                        $('#append').load('loadCat');
                    },
                    error: function (xhr, status, errorThrown) {
                        alert(JSON.parse(xhr.responseText).category[0]);
                    }

                });
                jQuery("#create").val('');
            });
        </script>

Second:

<script>
        $('[data-delete]').on('click', function (e) {
            e.preventDefault();
            var this_ = $(this);
            var token = $('input[name="_token"]').attr('value');
            var id = $(this).data("id");
            $.ajax(
                    {
                        url: "{{ url('/category') }}" + '/' + id + '/delete',
                        type: 'post',
                        dataType: "JSON",
                        data: {"id": id, '_token': token},
                        success: function (data) {
                            $(this_).parent().parent().remove();
                        }
                    });
            console.log("It failed");
        });
    </script>
  • 写回答

2条回答 默认 最新

  • weixin_33722405 2016-03-15 06:30
    关注

    It might be because you are binding click event on Dynamically generated element.

    You need to do something link

    $("#parent_id_or_class").on('click','.dynamicAddedElement_id_class',function(){
     // Code logic
    
    });
    

    More detail visit jQuery:How to bind click event on dynamically added element

    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效