2017-02-22 25 views
0

我目前有一個圖像,當我點擊圖像時,我想要獲取圖像的URL(這是src),然後從該圖像獲取與該圖像相關的信息我的mongodb數據庫。我試圖做的方式是點擊圖片,獲取網址,然後將網址傳回我的路線文件 - >執行數據庫查詢以獲取信息,然後傳回頁面,但信息爲空白Node.js ajax調用並顯示帶把手的結果

我的Ajax調用:

 $(function() { 
$(".image_selection").click(function() { 

    var idimg = $(this).attr('id'); 

    var data = {}; 
     data.img = idimg; 
     var source, template; 
       $.ajax({ 
        type: 'GET', 
        data: encodeURIComponent(idimg), 

         url: 'http://localhost:3001/new', 
         success: function(data) { 
          console.log('success'); 
          console.log(data); 

         } 
        }); 


    $("#load_art").css({"visibility":"visible"}); 
    //$("#load_art").html({data}); 

    $(".image_selection1").attr('src',idimg); 
    $('html,body').animate({ 
     scrollTop: $("#load_art").offset().top}, 
     'slow'); 
    }); 
}); 

});

我的路由文件:

app.get('/new', function(req, res){ 
    var obj = {}; 
    var img = req.body.img; 
    Images.find({'url':img}).limit(1).exec(function(err, docs){ 
     res.send({images:docs}); 
    }); 

}); 

把手視圖應該在技術上給我的原始數據,如果我寫{{圖片}},但沒有顯示出來。有任何想法嗎?

在控制檯:

success 

Array[1] 
0:Object 
width: bla bla, 
height: bla bla, 
etc for each object element returned from database 

回答

0

你離開你的數據晃來晃去。來自ajax調用的數據只能通過success函數獲得(它是異步的,這意味着它稍後會返回,並且可以從服務器獲得該數據時調用成功函數)。

所以,你需要在函數中添加邏輯觸發您的車把模板,返回的數據:

$(function() { 
    $(".image_selection").click(function() { 
    var idimg = $(this).attr('id'); 
    $.ajax({ 
     type: 'GET', 
     data: encodeURIComponent(idimg), 
     url: 'http://localhost:3001/new', 
     success: function (data) { 
     console.log(data); 
     var source = $("#image-template").html(); 
     var template = Handlebars.compile(source); 
     var html = template(data); 
     // you will now have some html that you will need to insert into your page 
     $(".someplace").innerHTML = html; 
     } 
    }); 
    }); 
}); 

您還需要提供合適的把手模板,這樣你就可以從客戶端更新頁面碼。你需要像這樣在你的HTML:

<script id="image-template" type="text/x-handlebars-template"> 
    {{#each items}} 
    {{width}},{{height}} 
    {{/each}} 
</script> 

你所得到的數據是一個數組,所以你需要使用一個#each車把構建。

+0

你能推薦一種方法來捕獲數據並將其傳遞給handlebars嗎? – user

+0

您的數據已經存在 - 'data'參數是您的ajax調用返回的數據。你可以把'console.log(data)'放在我的評論中看到的地方。之後,您將數據傳遞到您編譯的句柄模板。也許你可以在問題中包含你的把手視圖,我可以進一步指導你。 – rasmeister

+0

我想要做的是在ajax調用完成時顯示一部分句柄頁面(返回數據)。我更新了上面的代碼以顯示我想要實現的內容(滾動到頁面的部分,顯示我點擊的圖像,然後加載我從數據庫中檢索到的數據。 handlebars文件是/家 – user