tp框架之AJAX

实现一个AJAX添加并显示数据的例子

控制器

<?php
namespace Home\Controller;
use Think\Controller;
class AjaxController extends Controller
{
public function test()
{
$this->display();
} public function xianshi()
{
$n = D("Nation");
$attr = $n->select(); $this->ajaxReturn($attr); //ajax返回方法 } public function tianjia()
{
$this->display();
} public function tianjiachuli()
{
$n = D("Nation");
$n->create();
$r = $n->add();
if($r)
{
$this->ajaxReturn("OK","eval");
}
else{
$this->ajaxReturn("NO","eval");
}
}
}

显示界面

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script src="__PUBLIC__/js/jquery-1.11.2.min.js"></script>
</head> <body>
<table id="aa" width="100%" border="1" cellpadding="0" cellspacing="0"> </table>
<a href="__CONTROLLER__/tianjia">添加</a>
</body>
<script type="text/javascript">
$(document).ready(function(e) {
$.ajax({
url:"__CONTROLLER__/xianshi",
data:{},
type:"POST",
dataType:"JSON",
success: function(data){
var aa = "<tr><td>代号</td><td>名称</td><td>修改</td><td>删除</td></tr>";
var str = "";
for(a in data)
{
str = str+"<tr><td>"+data[a].code+"</td><td>"+data[a].name+"</td><td><a href='__CONTROLLER__/xiugai/code/"+data[a].code+"'>修改</a></td><td><a href='__CONTROLLER__/shanchu/code/"+data[a].code+"'>删除</a></td>";
}
$("#aa").html(aa+str);
}
})
});
</script>
</html>

添加页面

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script src="__PUBLIC__/js/jquery-1.11.2.min.js"></script>
</head> <body> <div>代号:<input type="text" id="code" /></div>
<div>名称:<input type="text" id="name" /></div>
<div><input type="button" id="btn" value="添加" /></div> <script type="text/javascript"> $("#btn").click(function(){
var code = $("#code").val();
var name = $("#name").val();
$.ajax({
url:"__CONTROLLER__/tianjiachuli",
data:{Code:code,Name:name},
dataType:"TEXT",
type:"POST",
success:function(data){
if(data=="OK")
{
window.location.href="__CONTROLLER__/test";
}
else
{
alert("添加失败");
}
}
});
}) </script>
</body>
</html>
上一篇:CentOS 6.9使用Setup配置网络(解决dhcp模式插入网线不自动获取IP的问题)


下一篇:Qt5.5.1 学习笔记