Rascal 目前正在托管我的简单网络服务器。这里我有一个使用 HTML textarea 标签的用户输入和一个提交按钮。但是,我不知道如何在用户提交数据后请求他们输入数据。我也没有看到太多有关它的文档,因此我们将不胜感激!
最佳答案
假设您使用库中的 Content
和/或 util::Webserver
来提供 Rascal 的内容,您始终提供 Response 类型的函数(请求)
到服务器。该函数执行从提供 index.html
到接收表单输入以及处理 XMLHttpRequest 的所有操作。您所要做的就是编写该函数的替代方案。
您可以获得的请求类型在 Content.rsc
中定义如下:
data Request (map[str, str] headers = (), map[str, str] parameters = (), map[str,str] uploads = ())
= get (str path)
| put (str path, Body content)
| post(str path, Body content)
| delete(str path)
| head(str path)
;
响应定义为:
data Response
= response(Status status, str mimeType, map[str,str] header, str content)
| fileResponse(loc file, str mimeType, map[str,str] header)
| jsonResponse(Status status, map[str,str] header, value val, bool implicitConstructors = true, bool implicitNodes = true, str dateTimeFormat = "yyyy-MM-dd\'T\'HH:mm:ss\'Z\'")
;
在下面的示例中,我使用了便利的实用函数,例如 Content::response(str)
,它用正确的 HTTP 状态和 mimetypes 包装了 html 字符串。
示例:
// this serves the initial form
Response myServer(get("/"))
= response("\<p\>What is your name?\</p\>
'\<form action=\"/submit\" method=\"GET\"\>
' \<input type=\"text\" name=\"name\" value=\"\"\>
'\</form\>
");
// // this responds to the form submission, now using a function body with a return (just for fun):
Response myServer(p:get("/submit")) {
return response("Hello <p.parameters["name"]>!");
}
// in case of failing to handle a request, we dump the request back for debugging purposes:
default Response myServer(Request q) = response("<q>");
现在我们可以直接从 REPL 提供此服务。内容将显示在 Eclipse 编辑器窗口或默认浏览器中,并且在 Rascal 的内部应用程序服务器中最后一次交互后将保持可用状态 30 分钟:
rascal>content("test", myServer)
Serving 'test' at |http://localhost:9050/|
或者我们可以自己提供服务,然后浏览到 http://localhost:10001
来测试服务器。完成后我们必须手动关闭它:
rascal>import util::Webserver;
ok
rascal>serve(|http://localhost:10001|, myServer)
ok
rascal>shutdown(|http://localhost:10001|)
关于request - 使用 Rascal 获取用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65228060/