我正在使用Slim框架,并试图通过一些php脚本建立并运行一个基本表单。Index.php包含一个表单,提交后将执行第二个名为request_variable.php的php脚本,该脚本将输出表单的内容
Index.php
<?php
use PsrHttpMessageServerRequestInterface as Request;
use PsrHttpMessageResponseInterface as Response;
require '../../vendor/autoload.php';
$app = new SlimApp;
$app->get('/',function(Request $request,Response $response){
$output = <<< HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="AUthor" content="tester" />
<title> form example</title>
</head>
<body>
<form action="request_variable.php" method="post">
<input type="text" name="firstname" placeholder="First Name" />
<input type="text" name"lastname" placeholder="Last Name" />
<input type="submit" name="submit" />
</form>
</body>
</html>
HTML;
echo $output;
});
$app->run();
request_variable.php
<?php
use SlimHttpRequest;
use SlimHttpResponse;
require '../../vendor/autoload.php';
$app = new SlimApp;
$app->post('/',function(Request $request,Response $response) use ($app)
{
$parameters = $request->getParsedBody();
echo $parameters['firstname'];
echo $parameters['lastname'];
}
$app->run();
问题
然后我测试index.php:
php-S localhost:8000 index.php
然后我在web浏览器中输入地址。表单是可见的,看起来还可以。我输入了我的名字和姓氏,但一旦我点击提交,我就会收到以下错误:
不允许使用方法,必须是以下方法之一:GET
作为一名php新手和web应用程序开发新手,我想知道为什么会发生这种情况?那么我需要使用get而不是post吗?或者这是另一个问题吗?提前谢谢。
使用map
代替get
和post
:
$app->map( [ "GET", "POST" ], "/", function ( Request $request,Response $response ) use ($app) {
if ( $request->isGet() ) {
$body = <<< ...; // your HTML
// point action to the route, not to file
// <form action="/" method="post">...
$response = $response->getBody()->write( $body );
}
if ( $request->isPost() ) {
$body = $request->getParsedBody();
$response = $response->withJson( $body );
}
return $response;
}
Map允许您在相同的函数(…函数(请求$req…((中处理相同的路由名称。我认为压缩我的代码很有用。我使用write
是因为你使用的是echo
。当我使用框架时,我会尝试使用框架的工具。经常是非常值得的!在我的日常工作中,对于UI路由,我要么返回slim/php-view
HTML/PHP文件,要么返回要在JavaScript应用程序中处理的JSON对象(通常是这样!(。
(地图-http://www.slimframework.com/docs/v3/objects/router.html)
(isPost和isGet-http://www.slimframework.com/docs/v3/objects/request.html)
(slim/php视图-http://www.slimframework.com/docs/v3/features/templates.html)
(正文和文字—http://www.slimframework.com/docs/v3/objects/request.html#the-请求主体(
(带Json->http://www.slimframework.com/docs/v3/objects/response.html(