简体   繁体   English

Ajax POST 路由 URL 在 CodeIgniter 4 中显示 404

[英]Ajax POST route URL showing 404 in CodeIgniter 4

I am having issues with Ajax and routes.我在使用 Ajax 和路由时遇到问题。 I am using Codeigniter 4.2.1.我正在使用 Codeigniter 4.2.1。

When I try to submit a login form using ajax, I get a 404 Not found error.当我尝试使用 ajax 提交登录表单时,出现 404 Not found 错误。

Below is the mentions code I am using:以下是我正在使用的提及代码:

The HTML form HTML 表单

<form id='loginFormScript' method='POST'>
<input type="email" id="emailLogin" name="emailLogin" >
<input type="password" id="passwordLogin" name="passwordLogin" >
<button type="submit">Submit</button>

The AJAX script AJAX 脚本

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
    $("#loginFormScript").submit(function(e) {
        alert("hello");
        e.preventDefault();
        $.ajax({
            url: '<?php echo base_url('save-user'); ?>',
            type: 'POST',
            data: $('#loginForm').serialize(),
            dataType: "json",
            success: function(data) {
               //SUCCESS CODE
            }
        });
    });
</script>

The route路线

$routes->setDefaultNamespace('App\Controllers');
$routes->setDefaultController('Home');
$routes->setDefaultMethod('index');
$routes->setTranslateURIDashes(false);
$routes->set404Override();
$routes->get('/', 'Home::index');
$routes->get('/login', 'Home::login');

$routes->get('/new1', 'Home::loginCheck');
$routes->get('/new', 'Home::login');
$routes->post("/save-user", "Home::saveUser");

My controller我的控制器

namespace App\Controllers;
class UserController extends BaseController
{
    public function __construct()
    {
            helper(['form', 'url']);
    }
    public function index()
    {
        return view('welcome_message');
    }
    public function login()
    {
      return view('login');
    }
    public function saveUser()
    {
            print_r($_POST);exit;
    }
}

Explanation:解释:

app/Config/Routes.php应用程序/配置/Routes.php

$routes->post("/save-user", "Home::saveUser");

The route definition above points to the saveUser method in the Home controller.上面的路由定义指向Home控制器中的saveUser方法。 Yet based on your uploaded source code, that method exists in an entirely different controller.然而,根据您上传的源代码,该方法存在于完全不同的控制器中。 Hence the 404 Not Found error.因此出现404 Not Found错误。

Solution:解决方案:

Instead, use this:✅相反,使用这个:✅

$routes->post("/save-user", "UserController::saveUser");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM