我在codeigniter 4中的ajax代码有问题。我有一个登录表单。我使用的代码在代码点火器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);
}
});
});
路由.PHP
$routes->get('admin/login', 'Admin/Ajax::login');
在codeigner4中,您必须使用与ajax请求中相同的方法,在本例中为POST
$routes->post('admin/login', 'Admin/Ajax::login');