call CodeIgniter Model with ajax

旧街凉风 提交于 2020-01-06 03:14:31

问题


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:

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

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.

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;
    }
}

回答1:


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,

source: https://www.codeigniter.com/user_guide/overview/appflow.html

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

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.




回答2:


No. It is not possible. All incoming server requests are routed to controllers.



来源:https://stackoverflow.com/questions/37514133/call-codeigniter-model-with-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!