gpt4 book ai didi

ajax - Liftweb : create a form that can be submitted both traditionally and with AJAX

转载 作者:行者123 更新时间:2023-12-03 23:56:10 24 4
gpt4 key购买 nike

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

当我使用 <lift:form.ajax> 构建表单时,表格的action设置为 javascript://这样它就不再在没有 JS 的情况下提交。如果我在没有明确 AJAX 支持的情况下构建表单,我不知道如何插入 AJAX 功能。

我想我可以构建一个 RESTful 接口(interface)(无论如何我们都必须构建它)并编写自定义 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>

关于ajax - Liftweb : create a form that can be submitted both traditionally and with AJAX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7784818/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com