繁体   English   中英

jQuery ajax无法从node.js中的视图文件工作?

[英]jQuery ajax is not working from view file in node.js?

我开始研究express nodejs,并从hbs视图陷入了ajax调用或jquery中。

这是我的控制器方法:

router.get('/', function(req, res) {
    console.log("home get request");
    res.render('index', { layout:'/layout/default' });  
});

router.post('/getPosts', function(req, res) {
    console.log("hi");
    var html = "";
    conn.query("CALL getPosts(?)",[req.session.user_id], function(err, rows){
        if(err){
            console.log(err);
        } else {
            if(rows) {
                for (var i in rows[0]) {
                    if(i.post_text != null && i.post_image != null) {
                        html = html + '<div class="post"><div class="user"><span>'+i.user_name+'</span></div><div class="post_text"><pre>'+i.post_text+'</pre></div><div class="post_image"><img src="/images.post_images/'+i.post_image+'" /></div><div class="create_time"><span>'+i.created_on+'</span></div></div>';
                    } else if(i.post_text == null) {
                        html = html + '<div class="post"><div class="user"><span>'+i.user_name+'</span></div><div class="post_image"><img src="/images.post_images/'+i.post_image+'" /></div><div class="create_time"><span>'+i.created_on+'</span></div></div>';
                    } else if(i.post_image == null) {
                        html = html + '<div class="post"><div class="user"><span>'+i.user_name+'</span></div><div class="post_text"><pre>'+i.post_text+'</pre></div><div class="create_time"><span>'+i.created_on+'</span></div></div>';
                    }

                }
                console.log(html);
                res.json(html);
                res.send(html);
            }
        }
    });
});

下面是我的HBS文件index.hbs:

<div class="container">
    <div class="pull-right"><button type="button" class="btn add">Create Post</button></div>
    <div class="container posts_div">
    </div>
</div>

<script type="text/javascript">
    $(document).ready(function(){
        $(document).on('load', function(){
            $.post('/home/getPosts',{test:"jeevan"},function(res){
                console.log(res);
                $(".posts_div").html(res);
            },'json');
        });

        $(".add").click(function(){
            alert("thats working");
        });
    });

<script>

我的路线是

app.use('/home', index);

我想在呈现索引视图时,ajax调用从数据库中获取所有帖子并显示在该视图文件中。 还有一件事是登录后在登录时出现索引页面上的获取请求,我将用户重定向到此URL,一个获取请求进入索引控制器,并在屏幕上查看渲染,但是我不知道为什么jQuery无法正常工作这里。

提前致谢。

您正在混淆documentwindow

$(document).ready(function() {
  // document is now ready
  $(document).on('load', function() {
    // doesn't work
  })
  $(window).on('load', function() {
    // window is now fully loaded
  });
});

文档 jQuery的$(document).ready

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM