2016-01-20 53 views
0

在SLIM 2中,我有一個小表單來顯示用戶名。如何在SLIM 2框架中顯示HTTP POST數據

我的index.php

$app = New \SlimController\Slim() 

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

在postpage.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'); 
} 

這裏是我的postpage.html

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

我得到這個錯誤:

異常 'ErrorException' 有消息 '未定義的變量:應用'

我想也嘗試var_dump($this->app->request->post("username")); ,我得到

異常「ErrorException '消息'未定義變量:此'

+1

您可能想澄清哪些版本的Slim使用2.0或3.0,我認爲它們之間存在細微的差異,可能會影響答案。 – Mikey

回答

1

Slim's(v 2.x)View類不存儲應用程序引用。 「最短」的方式獲得由內查看應用程序(然後請求對象)(除使用靜態Slim:getInstance法)

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

但這只是看起來像一個解決方法,而不是一個官方方式。

如果您認爲需要的數據,它應該得到它通過render方法:

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

如果這還不夠你,創建視圖的子類,持有引用到應用程序,並將其設置爲默認視圖。

+0

我得到'undefined $ app'錯誤,如何在我的控制器中調用$ app?我複製了我的索引文件,所以你可以看到我沒有傳遞變量$ app –

+0

謝謝,但它與$ this-> app-> request() - > post() –

0
//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(); 
    ?>