2016-02-22 40 views
-1

我使用node.js,express,jade和socket.io,我可以獲得在jade端運行的javascript代碼,但是我無法生成來自腳本的html。塊從javascript傳遞值到玉器

我不得不根據您的輸入更新我的問題。以下是文件:

server.js

app.get('/', function (req, res) { 
    res.sendfile(__dirname + '/index.html'); 
}); 

io.on('connection', function (socket) { 
     socket.emit('news', { hello: res}); // res is the reponse object 
     socket.on('my other event', function (res) { 
     console.log("socket.io connected and data sent to jade"); 
     }); 
    }); 

layout.jade:

doctype html 
html 
    head 
    title= title 

    script(src='components/jquery/dist/jquery.min.js') 

script(type='text/javascript' src='https://cdn.socket.io/socket.io-1.0.6.js') 
script(type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/jade/1.11.0/jade.min.js') 
script(type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/jade/1.11.0/runtime.min.js') 

    script. 
    var socket = io.connect('http://localhost:8898/'); 
    socket.on('news', function (data) { 
    var photo = data.hello.data[0].images.original.url;  
    }); 


body 
    block content 
     img(src="#{photo}") // <--- issue here, creates "undefined" image  

index.jade:

extends layout.jade 

    img(src="#{photo}") // my problem is here, creating <undefined> tags in html 

回答

0

你可以刪除現有的成分量,然後在jQuery AJAX回調中使用jQuery重新渲染。喜歡的東西..

玉:

標籤#數據

後:

腳本。

var socket = io.connect('http://localhost:8898/'); 
    socket.on('news', function (data) { 
     $('#data').text('');  
     $('#data').text(data); 
}); 
+0

也許,但是我從express生成的玉模板完全消失了。 – staminna

0

可能有點太明顯,但從這個例子來看,但我認爲腳本標記內的JS塊需要縮進。一直沒能測試,雖然

script. 

    var socket = io.connect('http://localhost:8898/'); 
     socket.on('news', function (data) { 
     console.log("socket.io.on data reaching jade"); 
     console.log(data); // prints fine, but to console only. 
     socket.emit('my other event', { my: data }); 
    }); 
+0

它似乎沒有區別。 – staminna

0

因爲你是從layout.jade和index.jade延長是你的孩子模板。你不需要聲明html是你的塊內容嗎?像這樣:

extends layout 

block content 
    #{data} // my problem is here, creating <undefined> tags in html 
     p #{data.stuff} 
     img(src="images/bird.jpg") // works 
+0

我根據您的輸入更新了我的問題。請檢查layout.jade最後一行中的註釋錯誤是「無法讀取屬性'hello'未定義的」 – staminna