用ajax调用CodeIgniter模型 [英] call CodeIgniter Model with ajax

查看:61
本文介绍了用ajax调用CodeIgniter模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在一个模型中调用一个函数,但是我想不通过控制器来调用它,这可能吗?下面提供的代码不起作用,我得到 404 Not Found

I'm trying to call a function in one of my model but I would like to do so without going through a controller, is that possible? The code provided below doesn't work, I get 404 Not Found

JavaScript:

Javascript:

$.ajax({
    type: "POST",
    url: "/myApplication/usersModel/get_cash_player",
    success: function(result){
       alert("ok");
    }
});

我的模型(位于usersModel.php中):

My model (located in usersModel.php) :

public function get_cash_player(){                
   $currentUserID = $this->usersModel->get_user_id();
   $query = $this->db
       ->select('cash')
       ->from('users')
       ->where('id_player', $currentUserID)
       ->get();
   return $query->row('cash');      
}

或者,我可以在模型中创建一个调用该方法的控制器,但我想知道此快捷方式是否可行.

Alternatively I could create a controller calling the method in the model but I would like to know if this shortcut is possible.

更新1:好的,接下来是下一个问题.对于某些控制器,我使用了自定义帮助器,因为我希望它们可以在多个控制器中使用.通过PHP调用它们时效果很好,但是我可以为上述(和注释中)的 get_cash_player 控制器创建一个并通过Ajax调用它吗?

Update 1: Okay, now comes the next question. For some of my controller I'm using a custom Helper because I want them available in several controllers. That works fine when calling them via PHP but can I create one for the get_cash_player controller mentioned above (and in the comments) and call it through Ajax?

我尝试过此方法,但仍然找不到:

I tried this but it is still not found:

if(!function_exists('get_cash_player')){
    function get_cash_player(){  
        $ci=& get_instance();
        $cash = $ci->usersModel->get_cash_player();
        return $cash;
    }
}

推荐答案

直接调用Model是不可能的,Controller是一个始终在View与Model之间进行处理的控制器.这是正确的Codeiginter MVC方法,

Directly calling the Model isnt possible, the Controller is the one always handling the process to and from View and the Model. This is the proper Codeiginter MVC approach,

来源: https://www.codeigniter.com/user_guide/overview/appflow.html

此链接也可以为您提供帮助 https://www.codeigniter.com/user_guide/overview/mvc.html

this link also may help you https://www.codeigniter.com/user_guide/overview/mvc.html

但是,您可以这样做:使用ajax函数调用控制器函数来传递数据.控制器将使用模型处理该过程,并将数据返回给ajax函数.

But, you can do like this: use your ajax function to call a controller function to pass data through. The controller will handle the process with the model, and return data back to the ajax function.

这篇关于用ajax调用CodeIgniter模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆