如何在 SLIM 2 框架中显示 HTTP POST 数据


How to display HTTP POST data in SLIM 2 framework

在SLIM 2中,我有一个显示用户名的小表单。

我的索引.php

$app = New 'SlimController'Slim()
//Define routes
$app->addRoutes(array('/' => array('get' => 'Home:indexGet','post' => 'Home:indexPost'),
   ));

在帖子中.php :

<form action="" method="post">
    <input type="text" name="username">
    <input type="text" name="password">
    <input type="submit">
</form>

这是我的控制器函数:

public function indexPostAction()
{
    $this->render('postpage');
}

这是我的帖子.html

var_dump($app->request->post("username"));

我收到此错误:

异常"

错误异常",消息为"未定义的变量:应用程序"

我试过

也试过var_dump($this->app->request->post("username")); 我得到

异常"

错误异常",消息为"未定义的变量:此"

Slim 的 (v 2.x) View 类不存储应用程序引用。从内部视图获取应用程序(然后是请求对象)的"最短"方法是(使用静态Slim:getInstance方法除外)是

$this->data->get('flash')->getApplication()->request()->post();

但这看起来只是一种解决方法,而不是官方方式。

如果您的视图需要数据,它应该通过 render 方法获取数据:

$app->render('template', array('postdata' => $app->request()->post()));

如果这对您来说还不够,请创建一个包含对应用的引用的 View 子类,并将其设置为默认视图。

 //First of all you did not set the action="" of your form in postpage.php so make it correct give the full route path like action="http://localhost/slim/index.php/showpostdata" (like if you are using wamp server and you have index.php in slim folder and showpostdata is your post route identifier) now try the following code or copy it and try it..
    //In postpage.php 
    <form action="http://localhost/slim/index.php/showpostdata" method="post">
        <input type="text" name="username">
        <input type="text" name="password">
        <input type="submit">
    </form>
    //In index.php which you will save in your slim folder
    <?php
      require 'vendor/autoload.php';
      $app = new'Slim'Slim();
    $app->post('/showpostdata', function () use ($app){
      $us=json_decode($app->request()->getBody(), true);
    //or
      $us=$_POST;
    //use one out of these above three or try all which gives you output..so In $us you will get an array of post data soo.. 
    $unm=$us["username"];
    $pwd=$us["password"];
    //now you have your post form data user name and password in variable $unm and $pwd now echo it...
    echo $unm."<br>";
    echo $pwd;
    });
     $app->run();
    ?>