Liftweb:创建一个可以传统和AJAX提交的表单

在Lift Web框架中可以创建通过 AJAX做出反应的表单(和链接),但是也可以在没有 Javascript支持的情况下工作?如果是这样,怎么办?

当我使用< lift:form.ajax&gt构建表单时,表单的动作设置为javascript://,以便不再提交JS.如果我没有明确的AJAX支持构建表单,我不知道如何插入AJAX功能. 我想我可以构建一个RESTful的界面(我们必须要建立这个),然后编写自定义Javascript来提交表单.我想避免代码重复,但是:如果可以使用相同的代码处理所有三个输入(RESTful,传统HTTP POST,AJAX),那将是最好的.

看看 http://demo.liftweb.net/form_ajax

FormWithAjax.scala

class FormWithAjax extends StatefulSnippet {
   private var firstName = ""
   private var lastName = ""
   private val from = S.referer openOr "/"

def dispatch = {
   case _ => render _
}

def render(xhtml: NodeSeq): NodeSeq =
{
   def validate() {
      (firstName.length, lastName.length) match {
         case (f, n) if f < 2 && n < 2 => S.error("First and last names too short")
         case (f, _) if f < 2 => S.error("First name too short")
         case (_, n) if n < 2 => S.error("Last name too short")
         case _ => S.notice("Thanks!"); S.redirectTo(from)
      }
   }

   bind( "form", xhtml, 
      "first" -> textAjaxTest(firstName, s => firstName = s, s => {S.notice("First name "+s); Noop}),
      "last" -> textAjaxTest(lastName, s => lastName = s, s => {S.notice("Last name "+s); Noop}),
      "submit" -> submit("Send", validate _)
   )
}

form_ajax.html

<lift:surround with="default" at="content">
  Enter your first and last name:<br>
  <form class="lift:FormWithAjax?form=post">
      First Name: <form:first></form:first>
      Last Name: <form:last></form:last>
      <form:submit></form:submit>
   </form>
</lift:surround>

并且这将工作没有javascript:

<form action="/form_ajax" method="post">
   <input name="F1069091373793VHXH01" type="hidden" value="true">
   First Name: <input value="" type="text" name="F1069091373788OVAAWQ" onblur="liftAjax.lift_ajaxHandler('F1069091373789N2AO0C=' + encodeURIComponent(this.value), null, null, null)">
   Last Name: <input value="" type="text" name="F1069091373790VANYVT" onblur="liftAjax.lift_ajaxHandler('F1069091373791CJMQDY=' + encodeURIComponent(this.value), null, null, null)">
   <input name="F1069091383792JGBYWE" type="submit" value="Send">
</form>
相关文章
相关标签/搜索