Eni*_*aRM 2 json codeigniter angularjs
让我先说一下我是AngularJS和CodeIgniter的新手.试图创建单页面应用程序.在中心它显示新闻故事.旁边是提交新故事的表格.我的故事从数据库显示得很好.但是当我尝试从侧面的表单创建新故事时,它会在数据库中输入0.我假设我的模型功能有问题.并且它可能是基本的,因为没有正确编码的信息在MVC之间传递.
的index.php
<div class="span2" ng-controller="NewStoryCtrl">
<h4>New Story</h4>
<form name="newStory">
<label for="title">Title: </label>
<input type="text" name ="title" ng-model="news.title" required>
<label for="text">Text: </label>
<textarea type="text" name="text" ng-model="news.text"required></textarea>
<button ng-click="createNews()">Submit</button>
</form>
Run Code Online (Sandbox Code Playgroud)
controller.js
function NewStoryCtrl($scope, $http) {
$scope.news = {title:$scope.title, text:$scope.text};
$scope.createNews = function(){
$http.post('/ci/index.php/news/create/',$scope.news);
};}
Run Code Online (Sandbox Code Playgroud)
news.php(控制器)
public function create() {
$this->news_model->set_news();
}
Run Code Online (Sandbox Code Playgroud)
news_model.php(型号)
public function set_news() {
$this->load->helper('url');
$slug = url_title($this->input->post('title'), 'dash', TRUE);
$data = array(
'title' => $this->input->post('title'),
'slug' => $slug,
'time' => time(),
'text' => $this->input->post('text')
);
return $this->db->insert('news', $data);
}
Run Code Online (Sandbox Code Playgroud)
模型中的东西是我最初的CI新闻教程的遗留物.这就是为什么我认为错误就在这里.将信息从controllers.js传递给模型的最佳方法是什么?
正如所料,我的问题是没有获得正确的数据类型.Controller期待一个变量,但是在Angular控制器中我把它作为JSON传递.我没有经历过解码.
news.php(控制器)
public function create() {
$data = json_decode(file_get_contents('php://input'), TRUE);
$this->news_model->set_news($data);
}
Run Code Online (Sandbox Code Playgroud)
然后在模型中,我只需要将它作为参数传递给set_news().我最后改变了一些变量名,只是为了个人澄清.
*news_model.php*
public function set_news($data) {
$this->load->helper('url');
$slug = url_title($data['title'], 'dash', TRUE);
$retval = array(
'title' => $data['title'],
'slug' => $slug,
'time' => time(),
'text' => $data['text']
);
return $this->db->insert('news', $retval);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4684 次 |
| 最近记录: |