【问题标题】:Fetching JSON data using Sencha Touch使用 Sencha Touch 获取 JSON 数据
【发布时间】:2013-03-20 09:43:13
【问题描述】:

如何在 Sencha Touch 中捕获使用 PHP 生成的 JSON 数据?有人知道这方面的好教程吗?

我正在尝试使用以下代码获取 JSON 数据

Ext.util.JSONP.request({
    url: 'proc/getEvents.php',
    callbackKey: 'callback',
    callback: function(data) {
        var lists = data.results;
        timeline.update(lists); // Update events lists
    }
});

我的 JSON 数据是这样的(由 getEvents.php 生成):

{
   "sample":[
      {
         "id":"1",
         "name":"131\/E Address",
         "desc":"This is where I live!!",
         "lat":"0",
         "lon":"0",
         "starttime":"0",
         "endtime":"0",
         "flag":"0"
      },
      {
         "id":"2",
         "name":"INOX",
         "desc":"Central Mall",
         "lat":"0",
         "lon":"0",
         "starttime":"0",
         "endtime":"0",
         "flag":"0"
      }
   ]
}

现在我想在模板中显示它。

tpl: [
        '<tpl for=".">',
            '<div class="details">',
                '<h2>{name}</h2>',
                '<p>{desc}</p>',
            '</div>',
        '</tpl>'
     ]

谁能帮我找出问题所在?我的 javascript 控制台说(使用 getEvents.php)

Resource interpreted as Script but transferred with MIME type text/html.
getEvents.php:1Uncaught SyntaxError: Unexpected token :

【问题讨论】:

    标签: json sencha-touch


    【解决方案1】:

    您需要您的 PHP 服务器以 JSONP 响应,而不是纯 JSON。 'P' 表示带有填充的 JSON。你指定的callbackKey需要PHP生成如下:

    callback({"sample":[
      {
         "id":"1",
         "name":"131\/E Address",
         "desc":"This is where I live!!",
         "lat":"0",
         "lon":"0",
         "starttime":"0",
         "endtime":"0",
         "flag":"0"
      }, { /*---etc---*/ });
    

    另外,为了消除 MIME 类型问题,在 PHP 中,在完成任何回显或打印之前放入此代码:

        header('Cache-Control: no-cache, must-revalidate');
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // never, ever cache
        header('Content-type: application/json');
    

    【讨论】:

      【解决方案2】:

      虽然使用 json 这可行

      echo utf8_encode(json_encode($json));
      

      当我移到 jsonp 时,我做到了

      echo $_GET['callback'] . '('.json_encode($results).')';
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-07-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多