Yii2:从控制器中弹出值获取值

时间:2016-01-19 11:44:57

标签: php post http-post yii2-advanced-app

我正在使用yii2-advanced-app&想发送用户名&使用post方法将密码发送到我的siteController。我不想在这里使用隐藏的表单字段。

我以这种方式尝试过:

我在index.php中的弹出窗口是 -

<form id = "userlogin" action = "index.php?r=site/loginpopup" method = "POST">
                    <label>Email / Username</label>
                    <input type="text" name="username" id="username"/>
                    <br />

                    <label>Password</label>
                    <input type="password" name="password" id="password"/>
                    <br />

                    <div class="checkbox">
                        <input id="remember" type="checkbox" />
                        <label for="remember">Remember me on this computer</label>
                    </div>

                    <div class="action_btns">
                        <div class="one_half"><a href="#" class="btn back_btn"><i class="fa fa-angle-double-left"></i> Back</a></div>
                        <div class="one_half last"><input type="submit" value="Search" onclick="getCred()"><a href="javascript: getCred()" name='login-button' class="btn btn_red">Login</a></div>
                    </div>
                </form>
                <script type="text/javascript">
                var userloginValidator = new Validator("userlogin");
                userloginValidator.addValidation("username","req", "Please enter the value for query");
                function getCred(){
                    var un = document.getElementById('username').value;
                    var pwd = document.getElementById('password').value;
                    alert(un);alert(pwd);
                    // window.location = "index.php?r=site/loginpopup&username="+un+"&password="+pwd;
                    if(document.userlogin.onsubmit()) {
                        document.userlogin.submit();
                    }
                    $.post("index.php?r=site/loginpopup", { username: un }, { password: pwd });
                    // jQuery.post('index.php?r=site/loginpopup',{ username: un }, { password: pwd });
                }
                </script>

控制器功能是 -

public function actionLoginpopup()
    {
$un = $_POST['username'];
echo $un;
        exit();
}

但是,它说 -

错误请求(#400) 无法验证您的数据提交。

1 个答案:

答案 0 :(得分:0)

我认为您无法使用jquery post方法发布多部分表单数据

尝试使用Yii2表单并放置此行

  

'enctype'=&gt; “多部分/格式数据”   在这样的表单选项中:

    $form = ActiveForm::begin([
    'id'      => 'userlogin',
    'method'  =>'post',
    'action'  => Url::toRoute['site/loginpopup'],
    'options' => [
        'enctype'          => 'multipart/form-data'
    ],
]); ?>

YiiForm