如何在codeigniter中查找是否是Ajax请求?

时间:2017-02-16 11:11:07

标签: php ajax codeigniter-3

我已通过ajax登录我的应用程序。当用户在登录前,尝试访问管理主页(http://localhost/ci3/admin/Adminhome),然后将其重定向到管理员登录页面(http://localhost/ci3/admin/Adminlogin)。以用户身份登录并尝试访问管理主页后,他将获得成功。现在我想找到ajax请求。我尝试了类似下面的内容,

Admin_controller

<?php
class Admin_controller extends CI_Controller{
    function __construct()
    {
        parent::__construct();
        $this->load->model("Adminmodel","",true);   
        $this->load->library('user_agent');

        $adminId =  $this->session->userdata('cp_adminid');

        if($adminId == null){
            if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH'])=='xmlhttprequest'){
                echo "it is ajax request";
            } else {
                echo "it is not ajax request";
            }
        } else {

        }
    }
?>

admin.js

$('#adminloginform').validate({

    errorClass: 'error',
    validClass: 'valid',
    errorPlacement: function(error, element) {
             error.insertAfter(element);
    },
    rules: {
        username:{
            required: true,

        },
        password:{
            required: true,
            minlength: 6,
        }
    },
    messages:{
        username: {
            required: "Email is required",

    },
        password: {
            required: "Password is required",
            minlength: "Atleast 6 characters",
    }
    },
    submitHandler: function(){
        var admin=$('#adminloginform').serializeArray();

        $.post("<?php echo base_url()?>admin/Adminlogin/auth",admin,function(data){

            if((data.result == 1) && (data.row.view == 1 || data.row.edit == 1 || data.row.add == 1 || data.row.deleteRole == 1 )){
                window.location="<?php echo base_url()?>admin/Adminhome";
            } else if (data.result == 1) {
                window.location="<?php echo base_url()?>admin/Userhomepage";
            } else {
                noty({ text: 'Username or Password is incorrect',type: 'error',modal:true,timeout:1000});
            }


            //$(".simplemodal-close").trigger("click");
        },"json");

    }

});

3 个答案:

答案 0 :(得分:1)

如果您的控制器仅用于ajax请求,那么您可以像这样构造构造子

public function __construct()
{
        parent::__construct();
        if(!$this->input->is_ajax_request())
            exit('No access allowed');
}

或者如果您只想检查一种方法,则

public function some_function()
{
        if(!$this->input->is_ajax_request()){

enter code here

        }
 }

答案 1 :(得分:0)

如果您在应用程序中使用它而不是为什么不创建标志。 当您从ajax调用时将其设置为true,并且默认情况下将其设置为false。

class Admin_controller extends CI_Controller{
    function __construct($AjaxFlag = false)
    {
        parent::__construct();
        $this->load->model("Adminmodel","",true);   
        $this->load->library('user_agent');

        $adminId =  $this->session->userdata('cp_adminid');

        if($adminId == null){
            if($AjaxFlag){
                echo "it is ajax request";
            } else {
                echo "it is not ajax request";
            }
        } else {

        }
    }

答案 2 :(得分:0)

 class PasswordChangeForm(forms.ModelForm):
    error_messages = {
    'password_mismatch': ("The two password fields didn't match."),
}
password1 = forms.CharField(
    label=("Password"),
    strip=False,
    widget=forms.PasswordInput,
    help_text=password_validation.password_validators_help_text_html(),
)
password2 = forms.CharField(
    label=("Password confirmation"),
    widget=forms.PasswordInput,
    strip=False,
    help_text=("Enter the same password as before, for verification."),
)

class Meta:
    model = User
    fields = ("username",)
    field_classes = {'username': UsernameField}

def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    if self._meta.model.USERNAME_FIELD in self.fields:
        self.fields[self._meta.model.USERNAME_FIELD].widget.attrs.update({'autofocus': True})

def clean_password2(self):
    password1 = self.cleaned_data.get("password1")
    password2 = self.cleaned_data.get("password2")
    if password1 and password2 and password1 != password2:
        raise forms.ValidationError(
            self.error_messages['password_mismatch'],
            code='password_mismatch',
        )
    self.instance.username = self.cleaned_data.get('username')
    password_validation.validate_password(self.cleaned_data.get('password2'), self.instance)
    return password2

def save(self, commit=True):
    user = super().save(commit=False)
    user.set_password(self.cleaned_data["password1"])
    if commit:
        user.save()
    return user