[英]Add script action for buttons in html with Vapor
我正在使用Swift 4和Vapor 2.0开发一个Web应用程序。 我有一个POST
请求的方法,它创建一个新用户:
builder.post("user", "createUser") { (request) -> ResponseRepresentable in
但我不知道如何在.leaf
文件中添加按钮动作来调用createUser
方法。 可以很容易地在.html
文件中添加JavaScript操作,例如<script src="js/index.js"></script>
。 但是对于Vapor,我在Vapor 2.0文档中没有看到任何提及
更新:
在@Caleb Kleveter的帮助下,现在它起作用了。 我更新了html
页面(它仅用于测试,因此它不是一个不错的页面)带来了希望:它对于在使用vapor
时面临同样问题的新手有帮助。
这是我的HTML内容:
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Responsive Login Form</title>
<link rel='stylesheet prefetch' href='http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css'>
<link rel="stylesheet" href="styles/app.css">
</head>
<body>
<link href='https://fonts.googleapis.com/css?family=Ubuntu:500' rel='stylesheet' type='text/css'>
<h3>
<form action="/user/createUser" method="POST" class="login-form">
<label for="username">Username:</label>
<input type="text" placeholder="Username" name="username"/>
<label for="password">Password:</label>
<input type="password" placeholder="Password" name="password"/>
<input type="submit" value="Login" class="login-button"/>
<form>
</h3>
<a class="sign-up">Sign Up!</a>
<br>
<h6 class="no-access">Can't access your account?</h6>
</div>
</div>
<!-- <div class="error-page">
<div class="try-again">Error: Try again?</div>
</div> -->
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js'></script>
<script src="js/index.js"></script>
</body>
</html>
可以像在HTML中一样将脚本添加到.leaf
文件中,只需添加脚本标记:
<script src="js/index.js"></script>
从查看代码,您想要的是一个将数据发布到服务器的form
。 您应该使用form
元素替换.login-form
div
:
<form action="/create-user" method="POST" class="login-form">
<label for="username">Username:</label>
<input type="text" placeholder="Username" name="username"/>
<label for="password">Password:</label>
<input type="password" placeholder="Password" name="password"/>
<input type="submit" value="Login" class="login-button"/>
<form>
<a class="sign-up">Sign Up!</a>
<h6 class="no-access">Can't access your account?</h6>
然后你应该能够使用request.body
访问路由方法中的表单数据:
func createUser(req: Request) throws -> ResponseRepresentable {
guard let password = req.body["password"]?.string,
let username = req.body["username"]?.string else {
throw Abort.badRequest
}
// The rest of your code goes here
}
我不确定这是否有用,我没有测试过,但我认为你明白了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.