Ajax 登录表单在 Codeigniter 4 中出现错误 404

Ajax login form getting error 404 in Codeigniter 4

我在 codeigniter 4 中的 ajax 代码有问题。我有一个登录表单。我使用的代码在 codeigniter 3 中运行良好。 这是代码。

PHP


public function login()
{
    if (! $this->request->isAJAX()) {
        //show404();
    }
    $this->validation->setRules([
        'email' => [
            'label'  => 'Email',
            'rules'  => 'required',
            'errors' => [
                'required' => '{field} some message.'
            ]
        ],
        'password' => [
            'label'  => 'Password',
            'rules'  => 'required|min_length[6]',
            'errors' => [
                'required' => '{field} some message.',
                'min_length' => '{field} some message.'
            ]
        ]
    ]);

    if ($this->validation->run() == FALSE) {
        if ($this->validation->hasError('email'))
        {
            echo sprintf('{"status":false,"message":"%s"}', addslashes((preg_replace('/\s+/', ' ', $this->validation->getError('email')))));
        }

        if ($this->validation->hasError('password'))
        {
            echo sprintf('{"status":false,"message":"%s"}', addslashes((preg_replace('/\s+/', ' ', $this->validation->getError('password')))));
        }
    }else {
        echo sprintf('{"status":true,"message":"%s"}', '<p>Success</p>');
    }
    exit();
}

HTML


<form action="<?= DOMAIN_NAME.'admin/login'; ?>" id="adminLoginFrom" name="adminLoginFrom" method="post" enctype="multipart/form-data">

JS

我贴在底部是因为我觉得这些链接文件中的一个可能与我在下面写的 ajax 块冲突


$("#adminLoginFrom").submit(function(e) {
    e.preventDefault();
    var form = $(this);
    var url = form.attr('action');
    $.ajax({
        url: url,
        type: "POST",
        data: $('#adminLoginFrom').serialize(),
        dataType: "json",
        success: function( response ) {
            console.log(data);
            console.log(response.success);
        }
    });
});

ROUTE.PHP


$routes->get('admin/login', 'Admin/Ajax::login');

在 codeigniter4 中,您必须输入与 ajax 请求中相同的方法,在本例中为 POST

$routes->post('admin/login', 'Admin/Ajax::login');