从React-AJAX中获取CodeIgniter PHP框架中的JSON数据

时间:2017-01-05 05:27:36

标签: php json ajax codeigniter reactjs

我在localhost:3000上运行了我的React应用程序 我的CodeIgniter API在localhost:8000上运行

我试图发送一个AJAX帖子请求并以JSON格式传递数据,但不知道如何在我的控制器中接收它...这就是我所拥有的

REACT

import React, { Component } from 'react';
import Request from 'superagent';

class App extends Component {
  constructor(){
    super()
      this.state = {
        email: '',
        password: ''      
    }
  }
  updateEmail(e){
    this.setState({
      email: e.target.value
    })
  }
  updatePassword(e){
    this.setState({
      password: e.target.value
    })
  }
  createUser(e){
    var query = 'star';
    e.preventDefault()
    console.log(this.state.email)
    var url = `http://localhost:8888/CI-React-API/React_api/create`;
    Request.post(url)
    .set('Content-Type', 'application/json')
    .send({ email: 'test' })
    .then((response) => {
      console.log(response)
    });
  }
  render() {
    return (
      <div className="App">
        <div className="App-header">
          <form onSubmit={this.createUser.bind(this)}>
            <input type="text"
             name="email"
             onChange={this.updateEmail.bind(this)} 
             value={this.state.email}
             placeholder="email"/>
             <br/>
            <input type="text"
             name="password" 
             value={this.state.password}
             onChange={this.updatePassword.bind(this)}
             placeholder="password"/>
             <br/>
            <input type="submit" value="submit"/>
          </form>
        </div>
      </div>
    );
  }
}

export default App;

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

class React_api extends CI_Controller {

    public function create()
    {

$obj=json_decode(file_get_contents('php://input'), true);
        // $email = $this->input->post('email');

        // echo $email;
        var_dump(file_get_contents('php://input'));
        die;
        // IDEA $this->load->view('welcome_message');
    }
}

1 个答案:

答案 0 :(得分:0)

更改网址

 var url = `http://localhost:8888/CI-React-API/React_api/create`;

 var url = 'http://localhost:8888/react_api/create';

OR 

 var url = '<?php echo base_url("react_api/create");?>';

在控制器中加载url助手,如下所示:

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

class React_api extends CI_Controller {

    function __construct()
    {
        parent::__construct();
        $this->load->helper('url');
    }

    public function create()
    {

        $email = $this->input->post('email');
        echo $email; 

$obj=json_decode(file_get_contents('php://input'), true);

        var_dump(file_get_contents('php://input'));
        die;
        // IDEA $this->load->view('welcome_message');
    }
}