codeigniter rest api和ajax

时间:2013-01-30 10:38:47

标签: ajax json codeigniter-restserver

我正在尝试访问我创建的其余api。当我键入以下内容时,它的工作非常好:

http://localhost:8080/rest/index.php/api/practice/test/name/Peter/surname/Potter/format/json

我得到了正确的json响应。现在我有一个网站,只是想使用ajax访问其余的api。这是代码:

$(document).on('pagebeforeshow','#page2',
    function(){
                $('#submit').click(function() 
                {
                    var name = $("#username").val();
                    var surname = $("#usersurname").val();

                    alert(name + " " + surname);
                    //alert("http://localhost:8080/rest/index.php/api/practice/test/name/"+name+"/surname/"+surname);

                    $.getJSON({ 
                           type: "GET",
                           crossDomain: true,
                           dataType: "jsonp",
                           url: "http://localhost:8080/rest/index.php/api/practice/test/name/"+name+"/surname/"+surname,
                           success: function(data)
                           {        
                             alert("workings");
                           }
});
                });         
              });

现在,当我使用此代码时,我得到404未找到的响应。当我得到那个网址时,我知道一个事实,我的意思是得到一个json响应。这是我的控制器来自其他api:

<?php  
require(APPPATH.'libraries/REST_Controller.php');  
class practice extends REST_Controller 
{  
    function test_get()
    {
        //echo "working fine ";
        $name = $this->get('name');
        $surname = $this->get('surname');
        //echo $name." ".$surname;
        $result = array('result' => "Working likes a boss ".$name." ".$surname);
        $this->response($result,200);
    }
}
?> 

2 个答案:

答案 0 :(得分:1)

在通话$.getJSON(...)中,您有网址

url: "http://localhost:8080/rest/index.php/api/practice/test/name/"+name+"/surname/"+surname

错过了上面的/format/json部分。

你也有

dataType: "jsonp",

不是json

<强>更新

我只是抬头jQuery.getJSON(),电话是

  

jQuery.getJSON(url [,data] [,success(data,textStatus,jqXHR)])

您似乎必须将通话更改为

$.getJSON("http://localhost:8080/rest/index.php/api/practice/test/name/"+name+"/surname/"+surname + "/format/json",
          function(data) { alert("workings"); });

或使用jQuery.ajax()

答案 1 :(得分:0)

你应该把标题设置为json:

<?php  
require(APPPATH.'libraries/REST_Controller.php');  
class practice extends REST_Controller 
{  
    function test_get()
    {
        //echo "working fine ";
        $name = $this->get('name');
        $surname = $this->get('surname');
        //echo $name." ".$surname;
        $result = array('result' => "Working likes a boss ".$name." ".$surname);
        header('Content-Type: application/json');
        echo json_encode( $result );
    }
}
?>