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 に答える