2015-11-03 124 views
0

此AJAX代碼是否有效?我希望視圖能夠繼續調用同一頁面,以便在用戶上傳圖片時,只需在該頁面上顯示給每個人,而不必每隔一段時間刷新一次。我是AJAX的新手,並且還在搞清楚。圖片確實出現,但不像我想要的那樣。他們沒有得到我的CSS樣式。如何快速查看ajax電話

<script> 
     $(function(){ 
      $.ajax({ url: 'http://localhost:3000/board' 
       , type: 'GET' 
       , dataType: 'html' 
      }) 
      .done(function(data) { 
       <% print.forEach(function(posts){ %> 
        $('html').append('<div class="post-container">'); 
         $('html').append('<h2> <%= posts.Title %> </h2>'); 
         $('html').append('<hr>'); 
         $('html').append('<a target="_blank" href=<%= "/viewer?id=" + posts.ID %>><img class="post-img" src=<%= "uploaded/" + posts.Img_path %>></a>'); 
        $('html').append('</div>'); 
       <% }); %> 
      }) 
      .fail(function() { 
       console.log("Something went wrong!"); 
      }); 
     }); 

    </script> 

這是路線:

router.get('/board', function(req, res){ 
    connection.query('SELECT * FROM posts, function(err, result){ 
     if(err){ 
      throw err; 
     }else{ 
      res.render('board', {print: result}); 
     } 
    }); 
}); 

回答

1

請您與以下.done()處理嘗試:

.done(function(data) { 
    <% print.forEach(function(posts){ %> 
     $('html').append('<div class="post-container">'+ 
       '<h2> <%= posts.Title %> </h2>'+ 
       '<hr>'+ 
       '<a target="_blank" href=<%= "/viewer?id=" + posts.ID %>><img class="post-img" src=<%= "uploaded/" + posts.Img_path %>></a>'+ 
       '</div>'); 
    <% }); %> 
}) 

否則您的通話ajax是好的。

+0

是的,它的工作原理。謝謝你,先生。但還有另一個問題。我在兩個選項卡上打開了該頁面。當一張圖片上傳到其中一個標籤時,它應該出現在另一個標籤上,但這不是發生了什麼。我必須刷新。這樣AJAX代碼就沒用了。那我能做些什麼? –

+0

謝謝。我對node.js並不熟悉,但在這個特定的場景中;你必須在每隔幾秒鐘後進行一次'ajax'調用,讓它說出20秒左右。由於頻繁的GET調用;最新的數據將在您的頁面上提供。 – vijayP