Sencha 2.0和Codeigniter RESTful API生成Uncaught SyntaxError:意外的令牌:

时间:2012-08-13 13:48:33

标签: javascript json api codeigniter sencha-touch

我正在尝试使用codeiniter restful api生成的(JSON)数据来提供sencha。我根据Net.tuts CI API TUTORIAL

执行了RESTful API

我收到错误Uncaught SyntaxError:意外的令牌: 这是我的Sencha代码和CI代码

CI CODE

function user_get()
    {
      if(!$this->get('id'))  
      {  
            $this->response(NULL, 400);  
      }  

        $user = $this->user_model->get( $this->get('id') );  

        if($user)  
        {  
            $this->response($user, 200); // 200 being the HTTP response code  
        }  

        else  
        {  
            $this->response(NULL, 404);  
        }     
    }

生成JSON

{
name: "ALEX JOHN",
country: "USA",
city: "NY"
}

SENCHA CODE

Ext.application({
    name: 'Sencha',

    launch: function() {

    Ext.create('Ext.DataView', {

    fullscreen: true,
    store: {
        autoLoad: true,
        fields: ['name', 'country','city'],

        proxy: {
            type: 'jsonp',
            url: 'http://localhost/rest_api/index.php/users/user/id/2',
            callbackKey: 'callback',
            callback: function(result) {
              console.log(result)  ;
            },
            reader: {
                type: 'json'
            }
        }
    },

    itemConfig: {
        tpl: '<p>{city}</p>'
    }
});
    }
});

我无法弄清楚该地区的来源。它来自我的JSON数据格式吗?sencha如何使用它?请有人帮忙。谢谢

1 个答案:

答案 0 :(得分:0)

如果您正在请求JSONP,则需要将返回的JSON包装在回调中。在您的控制器中,尝试使用以下命令替换有效的响应:

//Is the GET field callback set?  If so, wrap the user object in it
if (isset($_GET['callback'])){
  $user=$_GET['callback'].'('.json_encode($user).')';
  //And manually create the response 
  header("Status: 200 OK"."\r\n");
  header("Date: ".gmdate(DATE_RFC822)."\r\n");
  header("Content-Type: application/javascript charset=UTF-8\r\n");
  header("Content-Length: " . strval(strlen($user))."\r\n");
  echo $user;
} else  //Use thhe API to gnerate the response as normal
$this->response($user, 200);