我是代码点火器的新手,对于我的项目,我必须创建一个REST API。
我有一个有效的REST API。
从ajax调用调用API的正确方法是什么?
View ->REST
或
View -> Controller -> REST
如果是 <?php
defined('BASEPATH') OR exit('No direct script access allowed');
require APPPATH . '/libraries/REST_Controller.php';
class User extends REST_Controller {
function _construct(){
parent::_construct();
$this->load->database();
$this->load->model('usermodel');
}
public function user_get(){
$this->load->model('usermodel');
$requestType = $this->get('req');//get method request
switch ($requestType) {
case 'login':
$username = $this->get('un');
$password = $this->get('pw');
$user = $this->usermodel->getUser($username, $password);
if ($user){
$this->response($user, REST_Controller::HTTP_OK);
}else{
$this->response([
'status' => FALSE,
'message' => 'No users were found'
], REST_Controller::HTTP_NOT_FOUND);
}
break;
default:
break;
}
}
}
,如何从控制器调用REST API?
这是我的类,它扩展了用户的rest_controller
function signIn(){
var username = $('#signInUn').val();
var password = $('#signInPw').val();
$.ajax({
method: "GET",
url : "/infoshare/index.php/user/user/req/login/un/"+username+"/pw/"+password,
dataType: 'JSON',
success: function(data){
var response = data.response;
var status = data.status;
if(status == 200){
var userId = response[0].user_id;
//success of user
}else{
console.log(data);
}
},
error: function(status){
console.log("Error occured");
}
});
}
这是我的登录用户
登录页面的ajex调用redirect_to 'user#show'
答案 0 :(得分:0)
是的,你可以通过ajax调用rest apil。
$.ajax({
type: "GET",
data: {id:1123},
url: "http://localhost:8080/restws/json/user/get",
success: function(data){
alert(data);
}
});
传递方法所需的数据。如果POST或GET,请检查您的请求类型。