2016-11-07 29 views
1

展望更改玉賦值的變量與阿賈克斯後的結果,這樣的頁面的翡翠循環利用的新數據(更新只涉及到循環的DOM的部分,而不是渲染翻頁)。阿賈克斯結果變化玉分配變量

route.js

router.post('/initial', function(req, res) { 
    res.render('/page', {data: data}) 
}) 
router.post('/refresh', function(req, res) { 
    res.send(newdata) 
}) 

index.jade

block content 
    - var fluxdata = data 
    each item in fluxdata 
    span= item 
    div#button 

client.js

$(document).on('click', '#button', function() { 
    $.post('/refresh', function(newdata) { 
    var fluxdata = newdata 
    }) 
} 

我嘗試了諧音,但不知道我在正確的軌道上。看了一下週圍的互聯網和stackoverflow了一會兒,並找不到關於翡翠作業的類似問題。

回答

1
// Jade template 
block content 
    div(class="content") 
     - var fluxdata = data 
     each item in fluxdata 
      span #{item.id} : #{item.username} 
    div 
     button(id="add") POST Data 

after your template is rendered your html will look like this 


// HTML rendered 
<div class="content"> 
    <span>1 : Yves</span> 
    <span>2 : Jason</span> 
</div> 
<div> 
    <button id="add">POST DATA</button> 
</div> 

// backend code 

var users = [ 
    { 
     username: "Yves", 
     id: 1 
    }, 
    { 
     username: "Jason", 
     id: 2 
    } 
] 

router.get("/initial", function(request, responser) { 
    response.render("index", { data: users}) 
}) 


router.post("/refresh", function(request, responser) { 
    users.push({username: "Alex",id: 1}) 

    response.json({ data: users}) 
}) 



// Your jquery code 

$("#button").on('click', function(event){ 
    event.preventDefault() 
    $.post('/refesh', function(data) { 
     $(".content").html("") 
     for(var user in data) { 
      var span = $("<span>")   
      span.text(user.id + ": " + user.username) 
      $(".content").append(span) 
     } 

    }); 

}) 
0
in your get "/initial" route handler, your are rendering the 


res.render("/page", {data : data }) 

before the template name you musn't put the/and the template in witch you are trying to use data that at push to the view is index.jade 


router.post('/initial', function(req, res) { 
    res.render('index', {data: data}) 
}) 
+0

yvesdaxmaz,感謝指出了這一點。我斬斷我的應用程序,使問題變得更簡單,並且你是正確的,我需要在沒有/的情況下呈現索引。雖然你的回答並不回答這個問題。對於如何正確更改Jade變量賦值,您有任何建議嗎? – JasonA

+0

當你把你的Ajax請求,該模板在那個時候你呈現你有沒有玉模板中,有一個簡單的HTML頁面。你不能將你的ajax的結果替換爲你的模板。你必須以你操縱結果的方式編寫你的javascript,併爲你的dom添加一些標記。 – yvesdaxmaz

+0

和該請求被髮送必須返回數據的URL,而不是像你這樣的模板,在你的代碼一樣。還有些東西一樣JSON – yvesdaxmaz