0

我正在尝试访问我创建的 rest 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 not found 响应。当我到达那个 url 时,我知道一个事实,我打算得到一个 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);
    }
}
?> 
4

2 回答 2

1

在您的通话$.getJSON(...)中,您有 URL

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()

于 2013-01-30T10:51:52.003 回答
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 );
    }
}
?> 
于 2015-05-29T15:18:48.497 回答