【问题标题】:How to process a POST request in SWI-Prolog?如何在 SWI-Prolog 中处理 POST 请求?
【发布时间】:2013-01-16 07:12:35
【问题描述】:

我有一个这样的 HTML 表单:

<form action="test" method="post">
  <input name="first_name" type="text"/>
  <input name="last_name" type="text" />
  <input name="age" type="text" />
  <input type="submit" value="Send"/>
</form>

我如何获取输入字段的值并将它们打印在屏幕上,就像在任何其他过程编程语言(如 PHP、ASP 或 JSP)中一样?

我尝试通过以下方式解决问题:

:- use_module(library(http/thread_httpd)).
:- use_module(library(http/http_dispatch)).

:- http_handler(root(test), reply, []).
:- http_handler('test', reply, []).

server(Port) :-
        http_server(http_dispatch, [port(Port)]).

reply(Request) :-
        member(method(post), Request), !,
        http_read_data(Request, Data, []),
        format('application/x-www-form-urlencoded', []),
        format(Data).

这给我带来的只是500 代码的错误(内部服务器错误)。

【问题讨论】:

    标签: html forms post prolog swi-prolog


    【解决方案1】:

    您应该使用 http/http_client 库 (:- use_module(library(http/http_client)))。

    此外,我不确定有两个测试处理程序将如何工作。 最后,我认为 format(Data) 可能不起作用,特别是因为它预计会返回一个 html 文档。

    顺便说一句,要检索字段的值,您可以执行以下操作:

    http_read_data(Request, [first_name=FN, last_name=LN, age=A|_], []).
    

    我对 http prolog 库很陌生,我建议检查http://www.pathwayslms.com/swipltuts/html/

    【讨论】:

      【解决方案2】:

      基本上,您将像平常一样处理请求,检查请求中的 method(Method) 术语是否为 method(post)。

      http_read_data 将读取请求正文。 正文将像 URI 查询字符串一样编码,因此 uri_query_components/2 会将其转换为 Key=Value 术语列表

      ?- uri_query_components('a=b&c=d%2Bw&n=VU%20Amsterdam', Q)。 Q = [a=b, c='d+w', n='VU Amsterdam']。

      对于寻找类似信息的其他人 - 如果您的响应是 json,您可以使用 read_json_dict 将数据作为 dict 获取。

      【讨论】:

      • 安妮,说真的,这是一个链接唯一的答案;我应该对它投反对票,但不会。我知道你是谁,并且非常感谢你为 Prolog 尤其是 SWI-Prolog 社区所做的一切。这不是我正在寻找的答案。 (陈词滥调)。您的回答说它出现在3_2 中,但这不是正确的部分。有部分6.2. Handling POST requests。如果您将此作为真正的答案,将会有所帮助。谢谢。 :)
      • 已修复为更清晰和最新。我的网络教程已经过时了。
      【解决方案3】:

      我使用library(http/http_parameters)。有了这个,我就可以了

      load_graph(Request) :-
          http_parameters(Request,
                  [path(Path, [atom]),
                   aperture(Aperture, [integer])]),
      

      其中 load_graph 是表单的处理程序

      ...
      html(form([action(Ref)],
            dl([dt('Root Path'), dd(input([name=path, type=text, value=Default])),
                dt('Aperture'), dd(select([name=aperture], Aplist)),
                dt('Go!'), dd(input([type=submit, value='Load!']))
            ]))).
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-03-03
        • 2016-09-20
        • 1970-01-01
        • 1970-01-01
        • 2015-06-17
        • 2012-10-08
        • 1970-01-01
        • 2015-07-13
        相关资源
        最近更新 更多