【问题标题】:How to use Ajax and return view al the same time如何使用 Ajax 并同时返回视图
【发布时间】:2016-01-03 12:35:55
【问题描述】:

我的控制器中有一个登录方法,用于检查数据库中是否存在这样的用户。我在按下提交按钮时调用此方法。我同时从视图显示登录。

在我的情况下,如果有这样的用户,它不会显示消息。我想是因为在我的控制器中我加载了视图。

如果有这样的用户使用 Ajax 并且我像我的情况一样返回视图,我该如何显示此消息? 我正在使用Kohana。谢谢!

我的代码是:

$(document).ready(function(){

  $('#submit').on('click', function() {

    if(username.length === 0 || password.length === 0) {
      //...check if validation fails
    }
    else {
      $.ajax({
        url: "/admin/signin" ,
        type: "POST",
        data: {
          "username":username,
          "password":password
        },
        success: function(data) {
          if(data !== 'error') {

            window.location = "/admin/index";
          }
          else
          {
            alert('no such user');
          }
        }
      });
    }

  });

});
public function action_signin()
{

if ($_POST) {
$is_admin = Model_Admin::signin($_POST);           

print 'success';
} else {
print 'error';
}
}

$this->template->content = View::factory('admin/login_form');


}

【问题讨论】:

  • 你找到解决办法了吗?

标签: php jquery ajax kohana


【解决方案1】:

如果您不想加载“默认”模板,请尝试使用$this->auto_render = FALSE; kohana 控制器也有方法 is_ajax $this->request->is_ajax()

【讨论】:

    【解决方案2】:

    你的控制器代码会是这样的。

    public function action_signin()
    {
        if($this->request->is_ajax()){
            $this->auto_render = FALSE;
        }
    
        if ($_POST) {
            $is_admin = Model_Admin::signin($_POST);           
            if($is_admin){
                print 'success';
            } else {
               print 'error';
            }
        }else{
        $this->template->content = View::factory('admin/login_form');
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-16
      • 1970-01-01
      • 2020-07-21
      • 2012-02-09
      • 2012-03-20
      • 2015-05-26
      • 2021-02-25
      • 1970-01-01
      相关资源
      最近更新 更多