读取mysq数据库l数据,并使用dataview显示
来自《sencha touch权威指南》,约198页开始
通过php脚本,可以将mysql数据库的数据作为json数据格式进行读取。
(1)php代码(bookinfo.php):
<?php $link = mysql_connect("localhost","root","123456"); mysql_select_db("jiyale"); mysql_query("SET NAMES UTF8"); $result = mysql_query('select * from books',$link); if(!$result){ die('{"success":false,"message":"读取数据失败"}'); } if(mysql_num_rows($result)>0){ while($obj = mysql_fetch_object($result)){ $arr[] = $obj; } echo '{"success": true, "books": '.json_encode($arr).'}'; }else{ echo '{"success": false,"message":"读取数据失败","books":""}'; } ?>
(2)app.js代码:
Ext.require(['Ext.data.Store','Ext.data.reader.Xml','Ext.dataview.DataView','Ext.MessageBox']); Ext.application({ name: 'MyApp', icon: 'images/icon.png', glossOnIcon: false, phoneStartupScreen: 'images/phone_startup.png', tabletStartupScreen: 'images/tablet_startup.png', launch: function(){ Ext.define('BookInfo',{ extend: 'Ext.data.Model', config: { fields:['image_url','book_name','author','description'] } }); var bookStore = Ext.create('Ext.data.Store',{ model: 'BookInfo', autoLoad: true, proxy: { type: 'ajax', url: 'bookinfo.php', reader: { type: 'json', rootProperty: 'books' } }, listeners: { load: function(store,records,successful){ if(!successful){ Ext.Msg.alert(bookStore.getProxy().getReader().rawData.message); } } } }); var bookTemplate = new Ext.XTemplate( '<tpl for=".">', '<div class="Book_img"><img src="{image_url}" /></div>', '<div class="Book_info">', '<h2>{book_name}</h2><br /><h3>作者:{author}</h3>', '<p>{description:ellipsis(50)}</p>', '</div>', '</tpl>' ); var dataview = Ext.create('Ext.DataView',{ store: bookStore, itemTpl: bookTemplate, baseCls: 'Book', }); Ext.Viewport.add(dataview); } });
(3)index.html代码:
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>sencha touch</title> <link rel="stylesheet" type="text/css" href="css/sencha-touch.css" /> <script type="text/javascript" src="sencha-touch-debug.js"></script> <script type="text/javascript" src="app.js"></script> <style type="text/css"> .Book-item{padding:10px 0 30px 178px;border-top: 1px solid #ccc;} .Book-item h2{font-weight: bold;} .Book-item .Book_img{position: absolute;left: 10px;} .Book-item .Book_img img{max-width: 159px;} .Book-itme .Book_info{position: absolute;padding-left: 5px;font-size: 12px;} .x-item-selectex{background-color: blue;color: white;} </style> </head> <body> </body> </html>