2010-05-26 116 views
3

我是Lift的新手,我在Lift中使用bind,Ajax時有問題。Lift框架中的動態綁定

我想用動態的方式創建三個使用Ajax的下拉菜單。我用「Address」作爲例子來描述我試圖達到的目標。在拳頭,我只需要顯示默認設置爲「無」的「國家/地區」菜單。此時用戶可以選擇提交,如果她希望和地址被視爲默認。如果不是,她可以提供確切的地址。一旦她選擇了國家,應該顯示「州」菜單,並且一旦她選擇了「州」,應該顯示「縣」菜單。

在電梯演示示例的幫助下,我嘗試按如下方式創建靜態菜單。我創建了三個片段<select:country/>, <select:state/>, <select:county/>在我的.html文件和Scala代碼,我綁定如下:

bind("select", xhtml, 
    "system" -> select(Address.countries.map(s => (s,s)), 
         Full(country), s => country = s, "onchange" -> ajaxCall(JE.JsRaw("this.value"),s => After(200, replaceCounty(s))).toJsCmd), 
    "state" -> stateChoice(country) % ("id" -> "state_select"), 
    "county" -> countyChoice(state) % ("id" -> "county_select"), 
    "submit" -> submit(?("Go!"),()=>Log.info("Country: "+country+" State: "+state + " County: "+ county) 

相應replaceCounty,stateChoice,countyChoice都在我的類中定義。然而,當國家被選中時,只有國家通過阿賈克斯電話而不是縣來刷新。 Q1)有沒有辦法刷新基於國家菜單的菜單? Q2)如何按照前面的解釋動態創建菜單?

回答

1

使用SHtml.ajaxSelect作爲您的第一個選擇,而其他兩個使用的是靜態元素。當第一個選擇更改時,您將返回javascript以使用另一個SHtml.ajaxSelect調用的結果填充下一個選擇。

def countrySelect : NodeSeq = { 
    val countryOptions = List(("",""),("AR","AR")) 
    SHtml.ajaxSelect(countryOptions, Empty, { selectedCountry => 

    val stateOptions = buildStateOptions(selectedCountry) 
    SetHtml("state-select", SHtml.ajaxSelect(stateOptions, Empty, { selectedState => 
     // setup the county options here. 
    })) 

    }) 
} 

bind(namespace, in, 
    "country" -> countrySelect, 
    "state" -> <select id="state-select"/>, 
    "county" -> <select id="county-select"/>) 

在回調#ajaxSelect你可能會想保存任何已選擇的值,但是這是我採取的一般方法。

3

有,在做這只是提供一個很好的例子代碼:

http://demo.liftweb.net/ajax-form

如果你想更新多個下拉菜單爲AJAX更新的結果,你會想返回類似:

ReplaceOptions(...) & ReplaceOptions(...)