解析Extjs与php数据交互(增删查改)
编程学习 2021-07-05 09:49www.dzhlxh.cn编程入门
本篇文章是对Extjs与php数据交互(增删查改)进行了详细的分析介绍,需要的朋友参考下
代码如下:
<html>
<head>
//搜索暂时没做,数据是出来了,但是却没法显示
<link rel="stylesheet" type="text/css" href="./js/resources/css/ext-all.css"/>
<script type="text/javascript" src="./js/jquery.js"></script>
<script type="text/javascript" src="./js/ext-base.js"></script>
<script type="text/javascript" src="./js/ext-all.js"></script>
<script type="text/javascript" src="./js/ext-lang-zh_CN-min.js"></script>
<script type="text/javascript">
Ext.QuickTips.init(); //初始化快速提示对象
function test() {
Ext.Msg.alert('title','test-yii-ext');
}
function renderSex(value) {
if (value == 'male') {
return "<span style='color:red;font-weight:bold;'>红男</span><img src='./images/male.jpg' />";
} else {
return "<span style='color:green;font-weight:bold;'>绿女</span><img src='./images/female.png' />";
}
}
function init()
{
//1、创建url访问类。
var url = 'index.php';
var _proxy = new Ext.data.HttpProxy({url:url});
//2、数据问题参数
var _jsonProperty = "totalProperty";
//数据根目录参数
var _jsonRoot = "root";
//Record显示列表对应关系
var _record = [{name:'id'},
{name:'name'},
{name:'pass'},
{name:'sex'},
{name:'email'}];
//创建JSONReader对象,需要设置记录总数,根目录名称,记录映射
var _reader = new Ext.data.JsonReader({totelPropetty:_jsonProperty,root:_jsonRoot},_record);
/**
* 封装一个客户端的Record对象缓存,为GridPanel提供数据入口
* 需要两个必须的参数
* 1、提供数据的地址:Proxy 代理类
* 2、数据的读取方式:Reader 类,这里通过JsonReader读取
*/
var _store = new Ext.data.Store({
proxy:_proxy,
reader:_reader
});
/**
ColumnModel
* 数据在页面上显示标题信息,
* 顺序和Record对应
* sortable 是否排序
* dataIndex 进行对应的列,对应Record中的NAME
*
* handler方法中 第一个参数表示父类的对象,本例中为GridPanel对象。
* 第二个参数表示第几行。
* 第三个参数表示第几列。
*/
var _cm = new Ext.grid.ColumnModel([
new Ext.grid.RowNumberer(),
new Ext.grid.CheckboxSelectionModel(),
{header:"ID",dataIndex:"id",width:50,sortable:true,menuDisabled:true},
{header:"用户名",dataIndex:"name",width:80,sortable:true},
{header:"密码",dataIndex:"pass",width:175,sortable:true},
{header:"性别",dataIndex:"sex",width:145,sortable:true,renderer:renderSex},
{header:"电子邮箱",dataIndex:"email",width:150,sortable:true}
]);
/////////////////////////搜索
var logins = new Ext.form.FormPanel({
id:'myform',//分配表单id
title: '按用户名搜索',
width: 400,
defaultType: 'textfield',
frame: true,
// method: 'POST',
collapsible: true,//可折叠
bodyPadding: 5,
layout: 'column',//列布局
margin: '0 0 10 0',
items: [{
fieldLabel: '姓名',
labelWidth: 40,
id: 'name'
}],
buttons: [{
// xtype: 'button',
text: '搜索',
margin: '0 0 0 5',
handler: search
},{
// xtype: 'button',
text: '隐藏',
margin: '0 0 0 5',
handler: hide
}],
renderTo: "search"
})
logins.hide();
function hide()
{
logins.hide();
}
///////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
//获取数据
var ds = new Ext.data.Store({
//proxy告诉我们从哪获得数据,Ext.data.MemoryProxy专门解析js变量
//proxy:new Ext.data.MemoryProxy(data),
//通过http获取数据
proxy:new Ext.data.HttpProxy({
url:url}),
//获取json数据
reader:new Ext.data.JsonReader({
totalProperty:'totalProperty',
root:'root'
},Ext.data.Record.create([
{name:'id'},
{name:'name'},
{name:'pass'},
{name:'sex'},
{name:'email'}
]))
});
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//自动分页
var _pageSize = 16;
var _toolbar = new Ext.PagingToolbar({
store:ds,
pageSize:_pageSize,
displayInfo:true,
displayMsg:'显示第{0}条到第{1}条记录,一共{2}条',
emptyMsg:'暂无数据'
});
//顶部工具栏按钮
var t_toolbar = [
{id:"addData",text:"用户添加",handler:addUser},"-",
{id:"updateData",text:"用户修改",listeners:{"click":updateUser}},"-",
{id:"deleteData",text:"删除选中用户",handler:removeUser},"-",
{id:"test",text:"测试选中",handler:chkSelects},"-",
{id:"search",text:"搜索",handler:jump}
];
/**
* GridPanel对象
* 数据列表页面
* 必须设置 Store 数据访问对象和标题栏显示信息
* 即 Store和ColumnModel对象
*/
var _grid = new Ext.grid.GridPanel({
headerAsText: false, // 如果有标题栏, 隐藏标题栏
collapsible: true,//可折叠
height:500,
width:1100,
frame:true,//圆角边框
store:ds,
title:'测试yii整合Ext',
cm:_cm,
bbar : _toolbar,
tbar : t_toolbar
});
ds.load({params:{start:0,limit:_pageSize}});
_grid.render('test_id');
//_grid.render();
/* 用户信息录入框,验证 */
var fpanel;
function f(){
fpanel = new Ext.form.FormPanel
({
frame : true,//边框圆角并且有背景色
labelAlign : 'right',
waitMsgTarget : true,
autoScroll : true,
buttonAlign : 'center',
items : [
{xtype:"hidden",name:"id"},
{xtype:"textfield",fieldLabel:"用户名",name:"name",anchor : "-20",allowBlank:false,//是否允许为空
blankText:"用户名不允许为空!",labelWidth : 20},
{xtype:"radiogroup",fieldLabel:"性别",columns:2,allowBlank:false,blankText:"性别不允许为空!",items:[{boxLabel:'男',name:'sex',inputValue:'male'},{boxLabel:'女',name:'sex',inputValue:'female'}]},
{xtype:"textfield",fieldLabel:"密码",name:"pass",allowBlank:false,//是否允许为空
blankText:"密码不允许为空!",anchor : "-20"},
{xtype:"textarea",fieldLabel:"电子邮箱",name:"email",allowBlank:false,//是否允许为空
blankText:"邮箱不允许为空!",anchor : "-20"}
]
});
}
var win;
/* 增加用户 */
function addUser()
{
f();
win = new Ext.Window
({
title:"新增用户",
id:"win",
//animEl:"fly",
//layout:"fit",
width:350,
height:250,
closeAction : "close",
plain : true,
modal : true,// 模态窗口,当打开当前窗口时,后面的内容被遮挡
bodyStyle:"padding:3px 0 0 3px",
layout:"form",
labelWidth:55,
items:[fpanel],
buttons:[
{text:"保存", handler :function()
{
//在保存的时候,因为Id值为空,所以不能转换到后台,后台报类型转换异常,可以将Id设值为0,
//在后台处理的时候,对于值为0的Id不获取
fpanel.findByType("hidden")[0].setValue(0);
fpanel.getForm().submit({
url : "add.php",
method : "POST",
waitMsg : "保存数据...",
success : function(form, action) {
// 业务成功
Ext.MessageBox.alert('提示','添加成功!');
win.close();
ds.load({params:{ start:0,limit:_pageSize} });
},
failure : function(form, action) {
// 业务失败
obj = Ext.util.JSON.decode(action.response.responseText);
Ext.MessageBox.alert('提示', obj.errors.reason);
win.close();
ds.load({params:{ start:0,limit:_pageSize} });
}
});
}
},
{
text:"重置",handler:function()
{
fpanel.getForm().reset();
}
}
]
})
win.show();
// 因为重复使用window,有可能在修改后fpanel中还存在数据,所以要先重置
fpanel.getForm().reset();
}
/* 修改用户信息 */
function updateUser()
{
var win_2;
var a = 3;
f();
var selectedRecord = _grid.getSelectionModel().getSelected();
// 获得多个数据
if (selectedRecord == undefined || selectedRecord == null)
{
Ext.MessageBox.alert("提示", "请先选择一条记录!");
} else {
win_2 = new Ext.Window
({
title : "修改用户",
width : 350,
height : 250,
closeAction : "hide",
plain : true,
modal : true,// 模态窗口,当打开当前窗口时,后面的内容被遮挡
bodyStyle : "padding:3px 0 0 3px",
//layout : "form",
layout:"fit",
labelWidth : 55,
items : [fpanel],
buttons : [
{text:"修改", handler:function()
{fpanel.getForm().submit
({
url:"edit.php",
method:"POST",
waitMsg:"数据修改中...",
success:function(form,action)
{
win_2.hide();
Ext.MessageBox.alert("提示","数据修改成功");
_ds.reload();
},
failure : function(form, action) {
win_2.hide();
Ext.MessageBox.alert("提示","<font color='red'>数据修改失败</font>");
_ds.load();
}
});
}
},
{
text : "重置",handler:function()
{
fpanel.getForm().reset();
}
},
{
text: '关闭',handler: function()
{
win_2.close();
}
}
]
});
}
win_2.show();
// 将选中的数据load到window中显示
//alert(win_2);
win_2.getComponent(0).getForm().loadRecord(selectedRecord);
}
/* 删除用户 */
function removeUser(btn)
{
var selectedRecord = _grid.getSelectionModel().getSelected();
if (selectedRecord == undefined || selectedRecord == null)
{
Ext.MessageBox.alert("提示", "请先选择一条记录!");
} else {
Ext.MessageBox.confirm("提示信息", "确定要删除吗?", function(btn)
{
if (btn == "yes")
{
Ext.Ajax.request(
{
url:"del.php",
method:"POST",
params:{id : selectedRecord.data.id},
success:function(request, options)
{
var jsonRequest = Ext.util.JSON.decode(request.responseText);
if (jsonRequest == true)
{
Ext.Msg.alert("提示信息", "删除成功");
_grid.getStore().remove(selectedRecord);
ds.reload();
} else {
Ext.Msg.alert("提示信息", "<font color='red'>删除失败</font>");
}
},
failure : function()
{
Ext.MessageBox.show
({
title : "提示消息",
msg : "删除时发生错误"
});
}
});
}
})
}
}
function chkSelects()
{
var selects = _grid.getSelectionModel().getSelections();
alert("选中的总数为:"+selects.length);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function search(){
//fpanel.GridPanel().reset();init();
logins.getForm().submit({ //提交表单事件
//clientValidation: true,
method:"POST", //提交方式(POSTT和GET)
url:"search.php", //表单提交URL地址
waitMsg:"请稍等,正在搜索...", //提交未完成提示框内容
waitTitle:"正在搜索", //提示框标题信息
});
var url = 'search.php';
// store.proxy=new Ext.data.HttpProxy({url:url});
ds.reload();
//_proxy = new Ext.data.HttpProxy({url:url});
//ds.load({params:{start:0,limit:_pageSize}});
//_grid.render('test_id');
}
function jump()
{
logins.show();
}
//////////////////////////////
}
Ext.onReady(init);
</script>
</head>
<body>
<p style="height:10px;"></p>
<div id="test_id"></div>
<div id="search"></div>
</body>
</html>
Index.php文件
代码如下:
<?php
header("Content:text/html;charset=utf-8");
$link = mysql_connect("localhost","root","123456")or die('error'.mysql_error());
mysql_select_db("stu",$link);
mysql_query('set names utf8');
$sql = "select count(*) num from men";
$num = mysql_query($sql);
$count = mysql_fetch_array($num);
$start = $_POST['start'];
$limit = $_POST['limit'];
$sql2 = "SELECT * FROM men limit {$start},{$limit}";
/*
if (!$_POST)
{
$sql2 = "SELECT * FROM member";
} else {
$sql2 = "select * from member limit {$start},{$limit}";
}
*/
$data = array();
$result = mysql_query($sql2);
while(!!$info = mysql_fetch_array($result,MYSQL_ASSOC))
{
$data[] = $info;
}
//$j = json_encode($data);
$j = "{totalProperty:100,root:".json_encode($data)."}";
echo $j;
?>
Add.php文件如下:
代码如下:
<?php
header("Content:text/html;charset=utf-8");
$link = mysql_connect("localhost","root","123456")or die('error'.mysql_error());
mysql_select_db("stu",$link);
mysql_query('set names utf8');
$name = $_POST['username'];
$pwd = $_POST['password'];
$time = $_POST['regTime'];
$email = $_POST['email'];
/*
$name = 'aaaa';
$pwd = 'aaaa';
$time = '2011-12-31';
$email = 'aaaa';*/
$sql = "INSERT INTO men (username,password,regTime,email) VALUES ('{$name}','{$pwd}','{$time}','{$email}')";
//mysql_query($sql)
if (mysql_query($sql))
{
echo 'ok';
}
?>
Del.php文件如下:
代码如下:
<?php
header("Content:text/html;charset=utf-8");
$link = mysql_connect("localhost","root","123456")or die('error'.mysql_error());
mysql_select_db("stu",$link);
mysql_query('set names utf8');
$id = $_POST['id'];
$sql = "DELETE FROM men WHERE id={$id}";
if (mysql_query($sql))
{
echo 1;
} else {
echo 0;
}
?>
数据库文件men.sql
数据库名叫:stu
表名为:men
可以把狼蚁网站SEO优化的复制到一个文本文档里,然后新建stu数据库,导入就可以。
代码如下:
-- phpMyAdmin SQL Dump
-- version 2.11.2.1
-- http://www.phpmyadmin.net
--
-- 主机: localhost
-- 生成日期: 2012 年 01 月 11 日 10:02
-- 服务器版本: 5.0.45
-- PHP 版本: 5.2.5
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
--
-- 数据库: `stu`
--
-- --------------------------------------------------------
--
-- 表的结构 `men`
--
CREATE TABLE `men` (
`id` int(11) unsigned NOT NULL auto_increment,
`name` varchar(50) collate utf8_unicode_ci NOT NULL,
`pass` varchar(32) collate utf8_unicode_ci NOT NULL,
`sex` varchar(10) collate utf8_unicode_ci NOT NULL,
`email` varchar(50) collate utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=28 ;
--
-- 导出表中的数据 `men`
--
INSERT INTO `men` (`id`, `name`, `pass`, `sex`, `email`) VALUES
(1, '赵四', '123456', 'female', '646588973@qq.com'),
(2, '测试修改', '123456', 'male', 'test@qq.com'),
(8, '赵勇2', '123456', 'male', 'sfsf@qq.com'),
(9, '赵勇3', '123456', 'male', 'sfsf@qq.com'),
(10, '赵勇5', '123456', 'male', 'sfsf@qq.com'),
(11, 'asdfsf', 'asfsfsf', 'male', 'safsf'),
(18, '12', '123', 'male', '123'),
(19, '123', '123', 'female', '123'),
(20, '123123', '123', 'female', '123'),
(21, 'safdsdf', 'sdf', 'female', 'sdf'),
(22, 'sdfsdf', 'sdfsdf', 'male', 'sdf'),
(23, 'test', 'test', 'male', 'test@qq.com'),
(24, 'saf', 'asdfs', 'male', 'asdf'),
(25, 'dfgdfg', 'dfgdfg', 'male', 'dfgdfg'),
(26, 'ertert', 'erter', 'male', 'tertert'),
(27, '1asdf', 'sdf', 'male', 'sdf');