TP中讲的两种ajax方法

时间:2022-10-24 15:55:31
一、    
控制器中
public function add(){
$this->display();
}
    public function ajaxSave(){

        if(IS_AJAX){
echo '执行输入';
$model = M("tb_user");
$model->create();
$model->add();
echo '执行成功'; //这里会弹出一个框,把这两句一起输出
} }

view中

add.html

<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="__ROOT__/Common/jquery-1.8.3.min.js"></script> //引入jqery
<script>
$(function(){
$("#subFrom").click(function(){
//3个参数 js中的jq 获取所有的值 串行化 回调函数
$.post("{:U("index/ajaxSave")}",$("form").serialize(),function(data){
alert(data);
}) }); })
</script>
</head>
<body>
<form>
<input type="text" name="name" />
<input type="text" name="like_num" />
<input type="text" name="hobby" />
</form> <button id="subFrom">提交</button>
</body>
</html>

===========================================

===========================================

二、

控制器中写

 <?php
namespace Admin\Controller;
header("Content-type:text/html;charset=utf-8");
use Think\Controller;
class DataController extends Controller {
public function getAjax(){
if(IS_AJAX){ $data = 'ok'; //无
$this->ajaxReturn(['abcd'=>'abcd',"name"=>'zhangsan']);
}else{
echo 'hehe,不是AJAX请求'; }
} public function send(){ $this->display();
}
}

view

send.html

 <!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src='__ROOT__/business/Admin/view/js/jquery-1.8.3.min.js'></script> //引入jqery
<script>
$(function(){
$("#getAjax").click(function(){
//不写这个‘’也行 也是3个参数
$.get("{:U("Admin/data/getajax",'','')}",null,function(data){
$("<div>"+data.name+"</div>").appendTo("body");
})
}); }); </script>
</head>
<body>
<div>TODO write content</div>
<ul>
<li>__ROOT__</li>
<li>__APP__</li>
<li>__MODULE__</li>
<li>__CONTROLLER__</li>
<li>__PUBLIC__</li>
<li>__SELF__</li>
</ul> <button id='getAjax'>点击请求</button> //点击后,在后面添加 刷新后就没了
</body>
</html>

三、其他

手册的方法

//调用这个方法
public function send(){

 $data = 'ok';  //浏览器返回 "ok"

$data = ['abcd'=>'abcd',"name"=>'zhangsan'];      //浏览器返回  {"abcd":"abcd","name":"zhangsan"}

$this->ajaxReturn($data);
}

$this->ajaxReturn($data,xml); //返回下面的

<think>
<abcd>abcd</abcd>
<name>zhangsan</name>
</think>

-------------------------------------------------------