【问题标题】:JQuery doesn't work after adding ajax (Node.js, PUG)添加 ajax (Node.js, PUG) 后 JQuery 不起作用
【发布时间】:2018-09-12 01:45:38
【问题描述】:

我一直在尝试向我的博客文章网站添加类似功能。

当我点击类似链接的数字时,它应该运行 ajax 调用。 在我的 server.js 文件中,我有一个函数可以接收 mongodb 数据库中给定帖子的帖子请求更新点赞数。 我已将链接的名称属性设置为等于 post_id,以便我可以在数据库中修改该帖子。

html

head
    style
        include ../styles/home.css
    link(rel='stylesheet', href='https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css')
    script(src='https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js')
    script(src='https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js')
    script.
        $(document).ready(function(){
            $('.number_of_likes').click(function(e){
                e.preventDefault();
                alert('This part wont run');
                $.ajax(
                    type: 'POST',
                    url: '/like',
                    data: {'post_id' : $(this).attr('name')},
                    success: function(result){
                        alert('it works');
                    },
                    dataType: 'json'
                );
            });
        });

h2 Welcome to the main page
br
br
br
br
br
mixin postCard(postData)
    .post_container
        .row
            .col.s12.m6
                .card.blue-grey.darken-1
                    .card-content.white-text
                        span.card-title #{postData.title}
                        p= postData.content
                    .card-action
                        a(href='#') #{postData.username}
                        a(href='/delete_post/'+postData._id) Delete
                        a(href='' name=postData_id class='number_of_likes') #{postData.likes} 

each post in result
    +postCard(post)

但是点击事件不会被触发。

【问题讨论】:

    标签: javascript jquery node.js ajax pug


    【解决方案1】:

    问题可能是因为这是导致整个应用程序停止的无效语法:

    $.ajax(
        type: 'POST',
        url: '/like',
        data: {'post_id' : $(this).attr('name')},
        success: function(result){
            alert('it works');
        },
        dataType: 'json'
    );
    

    您需要将其作为对象传递,其中包含{} 之间的数据,如下所示:

     $.ajax({
        type: 'POST',
        url: '/like',
        data: {'post_id' : $(this).attr('name')},
        success: function(result){
            alert('it works');
        },
        dataType: 'json'
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-01
      • 2013-03-10
      • 2015-11-17
      • 2012-12-22
      • 1970-01-01
      • 2016-11-06
      • 2017-04-30
      • 1970-01-01
      相关资源
      最近更新 更多