簡體   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