我正在做本教程:http://code.tutsplus.com/tutorials/working-with-restful-services-in-codeigniter--net-8814(当然)我在Github-Repo(CodeIgniter-Bootstrap)上找到了CodeIgniter和Bootstrap。我只是不知道为什么我无法通过REST-URL访问我的REST服务器。任何教程都没有很好地提及路由。
这是应用程序/控制器目录中的Rest-Controller player.php:
<?php defined('BASEPATH') OR exit('No direct script access allowed');
require(APPPATH'.libraries/REST_Controller.php');
class Players extends REST_Controller {
function index() {
echo 'It works';
}
public function players_get() {
$this->response($this->db->select('playerName')->result());
}
public function player_get() {
if(!$this->get('playerName')) {
$this->response(NULL, 400);
}
$playerName = $this->input->get('playerName');
$this->response($this->db
->select('playerName')
->from('players')
->where('playerName', $playerName)
->get()
);
}
public function player_post() {
$playerName = $this->input->post('playerName');
$password = $this->input->post('password');
$player = array(
'playerName' => $playerName,
'password' => $password
);
// INSERT INTO 'players' (playerName, password) VALUES ($playerName, $password);
$this->db->insert('players', $player);
// On success, send back array with data
$this->response($player, 201); // Send an HTTP 201 Created
// On fail, send empty array
$this->response(array()); // HTTP 404 Not Found
}
}
我写信给routes.php:
$route['players'] = "players";
这是我写入config.php的内容:
$root = "http://".$_SERVER['HTTP_HOST'];
$root .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);
$config['base_url'] = $root;
$config['index_page'] = '';
我还没有型号。我只是想试试,如果我可以通过这个URL访问API:
myproject.cloudcontrolled.com/players
。我想,至少它会告诉我我在index() - 函数中的回声。但我得到的只是404。 最后,我需要做的是通过$ .ajax发送POST请求:
function myRegSubmit() {
$.ajax({
url: "http://myproject.cloudcontrolled.com/players/player",
data: {
playerName: $("#inputPlayer").val(),
password: $("#inputPassword").val()
},
type: "POST",
dataType: "json",
// code to run if the request succeeds;
// the response is passed to the function
success: function (json) {
$("#errorSpan").append(" It worked!");
//$( "<h1/>" ).text( json.title ).appendTo( "body" );
//$( "<div class=\"content\"/>").html( json.html ).appendTo( "body" );
},
// code to run if the request fails; the raw request and
// status codes are passed to the function
error: function (xhr, status) {
$("#errorSpan").append(" Sorry, there was a problem!");
},
// code to run regardless of success or failure
complete: function (xhr, status) {
$('#errorSpan').append(" The request is sent!");
}
});
}
这是我的第一个CodeIgniter项目和第一个REST-API,所以如果有人可以提供帮助,我会非常感激。我忽略了什么?我从小就坐在这! 非常感谢每一个有用的答案!
答案 0 :(得分:0)
:
$.ajax({
url: "http://myproject.cloudcontrolled.com/players/player",
它将数据发送到'玩家'控制器'播放器'方法,如果你想使用索引mehtod改变你的路线
$route['players/(:any)'] = "players"