连接AngularJS和CodeIgniter(GET调用工作但POST没有)

时间:2015-06-27 09:22:03

标签: angularjs codeigniter post

编辑:它适用于IE!所以我的Chrome和Mozilla必须阻止POST通话。 FYR:我在Chrome上安装了Allow-Control-Allow-Origin。

我想连接AngularJS(我在JavaScript框架中运行它 - 在MyDocuments上运行npm,gulp和bower)和CodeIgniter(在XAMPP上运行)。

GET调用工作正常(我通过AngularJS在屏幕上获取用户名和他们的城市)。

但是我有一个问题就是运行这个POST函数(它将新用户添加到数据库中):

$scope.addUser = function(name,city) {
    $http.post("http://localhost/test/index.php/usercontroller/addUser",{'name':name,'city':city})
        .success(function(response) {$scope.answer=response})
        .error(function(response) {alert('error');$scope.answer = response});
};

当我调用它时,控制台出错:

  

选项http://localhost/test/usercontroller/add 500(内部   服务器错误)(匿名函数)@ angular.js:10413sendReq @   angular.js:10232 $ get.serverRequest @ angular.js:9944processQueue @   angular.js:14454(匿名函数)@   angular.js:14470 $ get.Scope。$ eval @ angular.js:15719 $ get.Scope。$ digest   @ angular.js:15530 $ get.Scope。$ apply @ angular.js:15824(匿名   function)@ angular.js:23095eventHandler @ angular.js:3247(index):1   XMLHttpRequest无法加载   http://localhost/test/usercontroller/add。无效的HTTP状态代码   500

我的文件夹结构如下:

CODEIGNITER - CONTROLLER

的xampp / htdocs中/测试/应用/控制器/ usercontroller.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Usercontroller extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->model('usermodel');
        header('Access-Control-Allow-Origin: *');
        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
        header('Content-type: application/json');
        header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
    }

    public function index()
    {
        $data['include'] = 'user/index';
        $this->load->view('user/index', $data);
    }

    public function addUser()
    {
        $postdata = file_get_contents("php://input");
        $request = json_decode($postdata);
        $name = $request->name;
        $city = $request->city;
        $id = $this->usermodel->addUser($name,$city);
        if($id)
        {
            echo '{"status" : "success"}';
        }
        else
        {
            echo '{"status" : "failure"}';
        }
    }

    public function getCities()
    {
        $cities = $this->usermodel->getCities();
        echo json_encode($cities);
    }

    public function getUsers()
    {
        $users = $this->usermodel->getUsers();
        echo json_encode($users);
    }

}   

CODEIGNITER - MODEL

的xampp / htdocs中/测试/应用/模型/ usermodel.php

<?php if (!defined('BASEPATH')) exit('No direct script allowed');

class Usermodel extends CI_Model {

    public function __construct()
    {
       parent::__construct();
    }

    public function addUser($name,$city)
    {
        $data = array('name' =>$name,'city' => $city);
        $this->db->insert('user',$data);
        $insert_id = $this->db->insert_id();
        return $insert_id;
    }

    public function getCities()
    {
        $sql='SELECT city FROM user';
        $query = $this->db->query($sql);
        $city = array();
        foreach($query->result() as $row)
        {
            $city[]=array("city" => $row->city);
        }
        return $city;
    }

    public function getUsers()
    {
        $sql='SELECT * FROM user';
        $query = $this->db->query($sql);
        $user = array();
        foreach($query->result() as $row)
        {
            $user[]=array(
                "name" => $row->name, 
                "city" => $row->city
            );
        }
        return $user;
    }

}

ANGULAR - APP

我的文档/测试/ SRC / app.js

angular.module('app', []);

ANGULAR - INDEX.HTML

我的文档/测试/ SRC / index.html中

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">

    <title>Test project</title>

    <link rel="stylesheet" href="../bower_components/bootstrap/dist/css/bootstrap.min.css">

    <script src="../bower_components/angular/angular.js"></script>

    <script src="js/all.js"></script>

</head>

<body ng-app="app">
    <div ng-controller="MainController">


        <form novalidate>
            <label>Name:</label>
            <input type="text" ng-model="name"/>
            <div>{{name}}</div>
            <label>City:</label>
            <input type="text" ng-model="city"/>
            <div>{{city}}</div>
            <button ng-click="addUser(name,city)">Submit</button> 
            <div>Answer:{{answer}}</div>
        </form>

        <h3>Users</h3>
        <ul>
            <li ng-repeat="user in users track by $index">{{ user.name }}, {{user.city}}</li>
        </ul>

    </div>
</body>
</html>

ANGULAR - CONTROLLER

我的文档/测试/ SRC /组件/ MainController.js

angular.module('app').controller('MainController', function($scope, $http) {

    $http.get("http://localhost/test/index.php/usercontroller/getUsers")
        .success(function(response) {$scope.users = response});

    $http.get("http://localhost/test/index.php/usercontroller/getCities")
        .success(function(response) {$scope.cities = response});

    $scope.addUser = function(name,city) {
        $http.post("http://localhost/test/index.php/usercontroller/addUser",{'name':name,'city':city})
        .success(function(response) {$scope.answer=response})
        .error(function(response) {alert('error');$scope.answer = response});
    };

});

我做错了吗?

我在MyDocuments和XAMPP上的CodeIgniter上有一个JavaScript框架是否有问题。我也尝试将整个JavaScript文件夹(带有npm,gulp和bower)放在XAMPP上(不知道这是不是一个好主意,但我还是试过了)我得到同样的500错误运行addUser()POST调用。

我尝试的另一件事是我在xampp / htdocs上直接放置了一个超级简单的angular.html(附在这篇帖子的底部),在这种情况下,POST调用完美无缺。

所以我猜JavaScript(angular,npm,gupl,bower)和CodeIgniter文件夹之间的通信存在问题。

任何想法可以做些什么来连接它们? GET调用正在工作,所以我想应该有一个POST调用的解决方案。提前感谢您提供任何提示。

直接在XAMPP / HTDOCS上的超简单角度.HTML

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
  </head>

<body>
    <div ng-app="app" ng-controller="MainController">

        <form novalidate>
            <label>Name:</label>
            <input type="text" ng-model="name"/>
            <div>{{name}}</div>
            <label>City:</label>
            <input type="text" ng-model="city"/>
            <div>{{city}}</div>
            <button ng-click="addUser(name,city)">Submit</button> 
            <div>Answer:{{answer}}</div>
        </form>

        <h3>Users</h3>
        <ul>
            <li ng-repeat="user in users track by $index">{{ user.name }}, {{user.city}}</li>
        </ul>
    </div>

<script>

    var app = angular.module('app', []);

    app.controller('MainController', function($scope, $http) {
            console.log('delam');
            $http.get("http://localhost/ekohrana/index.php/usercontroller/getUsers")
        .success(function(response) {$scope.users = response});

        $scope.addUser = function(name,city) {
         $http.post("http://localhost/ekohrana/index.php/usercontroller/addUser",{name:name,city:city})
         .success(function(response) {$scope.answer=response})
         .error(function(response) {alert('error');$scope.answer = response});
         };

    });

</script>

</body>
</html>

1 个答案:

答案 0 :(得分:0)

问题是你正在发出CORS post请求,因此浏览器试图在POST的同一个url上对你的后端进行第一次OPTIONS调用,当你在OPTIONS请求上没有正确响应时,你的前端将会失败。

   function __construct() {

        header('Access-Control-Allow-Origin: *');
        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method");
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
        $method = $_SERVER['REQUEST_METHOD'];
        if($method == "OPTIONS") {
            die();
        }
        parent::__construct();