Как связать сенсорное приложение sencha с базой данных mysql с помощью бэкэнда PHP?

Я знаю, что на это, возможно, ответили в другом месте, но я все еще застрял и уже проверил много источников. У меня уже есть мой вид списка Sencha, модель и настройки магазина вместе с базой данных mysql с преобразованием PHP + json. Но он все равно не будет отображать результат в моем списке. Мое приложение sencha работает без ошибок вообще. Проведя много исследований, я понял, что определенно делаю что-то не так, определяя корневое свойство в своем классе магазина. Ниже приведен мой код PHP + json с запросами mysql для извлечения данных из базы данных:

<?php
header('Content-Type: text/javascript; charset=UTF-8');

ini_set("display_errors", true);
ini_set("html_errors", true);

//checking connection and connecting to a database
require_once('connection/config.php');
//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}

//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}

//variables initialization
$out = "";
$action = "";
$data = "";

//check if read is set from the Teams class
if (isset($_REQUEST["action"])){
$action = $_REQUEST["action"];
}
switch ($action) {
case "read": $out = read_this();
break;
}
echo utf8_encode($out);

//using function read_this() to retrieve teams from the tb_teams table then convert into json data
function read_this(){
$result=mysql_query("SELECT home_team_name FROM tb_teams")
or die("There are no records to display ... \n" . mysql_error());

$num = mysql_num_rows($result);

$i = 0;

$eData = array("count" => $num, "fixtures" => array());

while ($row = mysql_fetch_assoc($result)){
$eData["fixtures"][$i] = $row;
$i++;
}

return $_REQUEST['callback'] . '(' . json_encode($eData) . ');';
}
?>

Мой модельный класс:

    Ext.define('App.model.Team',{
extend: 'Ext.data.Model',

config: {
fields: [{name: 'home_team_name', type: 'string' }]
},
});

Мой магазин класс:

Ext.define('App.store.Teams',{
extend: 'Ext.data.Store',

config: {
model: 'App.model.Team',
sorters: 'home_team_name',
grouper: function(record) {
return record.get('home_team_name')[0];
},
proxy: {
type: 'scripttag',
url: 'http://127.0.0.1/backend/store.php',
reader: {
type: 'json',
root: 'fixtures'
},
extraParams: {
action: 'read'
}
}
}
});

И мой список просмотра класса:

Ext.define('App.view.TeamList',{
extend: 'Ext.List',
xtype: 'teamlist',

config: {
title: 'Teams',
//loading data from Teams store into a List item and apply some properties
grouped: true,
indexBar: true,
itemTpl: '{ home_team_name }',
store: 'Teams',
}
});

Пожалуйста, кто-нибудь посоветует, где именно я делаю не так? Заранее спасибо.

0

Решение

У меня недостаточно репутации, чтобы комментировать.

Я думаю, что вы должны использовать itemTpl: '{ name}' на месте itemTpl: '{ home_team_name }', Потому что вы объявили name как поле в вашей модели.

Ext.define('App.view.TeamList',{
extend: 'Ext.List',
xtype: 'teamlist',

config: {
title: 'Teams',
//loading data from Teams store into a List item and apply some properties
grouped: true,
indexBar: true,
itemTpl: '{ name}',
store: 'Teams',
}
});
0

Другие решения

После долгих наблюдений я обнаружил, что проблема на самом деле заключалась в преобразовании PHP в json (адаптировано из сенсорной документации sencha) и в том, как я обрабатывал обратный вызов в классе store.

Рабочий код PHP:

<?php
header('Content-Type: text/javascript; charset=UTF-8');

ini_set("display_errors", true);
ini_set("html_errors", true);

//checking connection and connecting to a database
require_once('connection/config.php');
//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}

//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}

//variables initialization
$out = "";
$action = "";

//check if read is set from the Teams class
if (isset($_REQUEST["action"])){
$action = $_REQUEST["action"];
}
switch ($action) {
case "read": $out = read_this();
break;
}
echo utf8_encode($out);

//using function read_this() to retrieve teams from the tb_teams table then convert into json data
function read_this(){
$result=mysql_query("SELECT home_team_name FROM tb_teams")
or die("There are no records to display ... \n" . mysql_error());

$arr = array();

while($obj = mysql_fetch_object($result)) {
$arr[] = $obj;
}

$callback = $_REQUEST['callback'];
if ($callback) {
header('Content-Type: text/javascript');
return $callback . '(' . json_encode($arr) . ');';
} else {
header('Content-Type: application/x-json');
return json_encode($arr);
}
}
?>

В классе store мне пришлось установить значение true для автоматической загрузки, чтобы включить автономное чтение данных json:

Ext.define('App.store.Teams',{
extend: 'Ext.data.Store',

config: {
model: 'App.model.Team',
sorters: 'home_team_name',
grouper: function(record) {
return record.get('home_team_name')[0];
},
proxy: {
type: 'scripttag',
url: 'http://127.0.0.1/backend/store.php',
reader: {
type: 'json',
root: 'fixtures'
},
extraParams: {
action: 'read'
}
}
autoLoad true,
}
});

Еще раз спасибо всем, кто пытался помочь. Я надеюсь, что это сэкономит другим партнерам много времени.

0

Предполагая, что вы получаете правильный сервер форм json; Иногда добавление высоты и ширины в список может помочь.

width: "95%",
height: "95%",
-1
По вопросам рекламы [email protected]