Home  >  Article  >  PHP Framework  >  Do you use ajax method in thinkphp?

Do you use ajax method in thinkphp?

WBOY
WBOYOriginal
2022-06-16 17:47:422727browse

The ajax method is used in thinkphp; thinkphp uses ajax in the same way as PHP uses ajax. The difference is that the url in PHP's ajax points to a page, while the url in thinkphp needs to point to an operation method, which can be used Ajax returns the specified data, returns the modification of the data type, etc.

Do you use ajax method in thinkphp?

The operating environment of this article: Windows 10 system, ThinkPHP version 5, Dell G3 computer.

Do you use ajax method in thinkphp?

Use ajax method in thinkphp

thinkphp uses ajax in the same way as before. The difference is that before The url in ajax points to a page, while the url in thinkphp needs to point to an operation method.

1. thinkphp uses ajax to return data

1. First write a method in AdminControllerMainController.class.php

public function testajax()//ajax测试方法
    {
        $this->show();
    }

2. In the AdminViewMain file Create the corresponding display page testajax.html

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="__PUBLIC__/js/jquery-1.11.2.min.js"></script><!--jquery文件放在public/js里面。__PUBLIC__找到public目录-->
<title>无标题文档</title>
</head>
<body>
    <select id="nation"></select>
</body>
<script type="text/javascript">
        $.ajax({
            url:"__CONTROLLER__/ajaxchuli",//这里指向的就不再是页面了,而是一个方法。
            data:{},
            type:"POST",
            dataType:"JSON",
            success: function(data){
                //alert(data[0].code);//这里要用索引,使用eq读取不出来数据。
                var str="";
                for(a in data)
                {
                    str = str+"<option value=&#39;"+data[a].code+"&#39;>"+data[a].name+"</option>";
                }
                $("#nation").html(str);
            }
        })
</script>

3. Write the ajax processing method in AdminControllerMainController.class.php

public function ajaxchuli()
    {
        $n = D("Nation");//造一个nation表的模型对象
        $attr = $n->select();
        
        $this->ajaxReturn($attr);//ajax返回数据的方式,用ajaxReturn。
    }

4. In this way, the data will be displayed on the page

2. Modification of ajax return data type

In thinkphp, ajax returns JSON data by default, which can be set by configuring DEFAULT_AJAX_RETURN. The setting method is as follows

// 指定XML格式返回数据
$data[&#39;status&#39;] = 1;
$data[&#39;content&#39;] = &#39;content&#39;;
$this->ajaxReturn($data,&#39;xml&#39;);

If it is XML mode, it will be automatically encoded into an XML string. If it is EVAL mode, only string data data will be output.

Example:

public function ajaxchuli()
{
$this->ajaxReturn("hello","eval");//将返回数据的类型更改成字符串
}

At the same time, we also need to change the data type in ajax to TEXT

<script type="text/javascript">
        $.ajax({
            url:"__CONTROLLER__/ajaxchuli",//这里指向的就不再是页面了,而是一个方法。
            data:{},
            type:"POST",
            dataType:"TEXT",
            success: function(data){
                alert(data);//输出结果就是hello
            }
        })
</script>

3. Use ajax and create (automatic collection form) to send data to the database Add data

1. Write the access method first

public function addajax()
    {
        $this->show();
    }

2. Write the accessed page

<body>
<div>代号:<input type="tel" id="code" /></div>
<div>名称:<input type="tel" id="name" /></div>
<div><input type="button" id="btn" value="添加" /></div>
</body>
<script type="text/javascript">
$("#btn").click(function(){
        var code = $("#code").val();
        var name = $("#name").val();
        $.ajax({
                url:"__CONTROLLER__/addchuli",
                data:{Code:code,Name:name},//要用create方法,这里的列名就要和数据库中的列名一样,这里的首字母要大写。
                type:"POST",
                dataType:"TEXT",
                success: function(data){
                    alert(data);
                }
            })
    })
</script>

3. Write the ajax processing method

public function addchuli()
    {
        $n = D("Nation");
        $n->create();//自动收集表单
        $r = $n->add();//调用添加的方法
        if($r)
        {
            $this->ajaxReturn("OK","eval");//如果添加成功输出“OK”,eval代表数据类型为字符串。
        }
        else
        {
            $this->ajaxReturn("NO","eval");//如果添加失败,就输出”NO“。
        }
    }

4. Use ajax for paging in thinkphp. Mainly pay attention to how third-party classes are referenced.

1. First make a method xianshi();

public function xianshi()
    {
        $n = D("chinastates");//造chinastates表的对象
        $shuliang = $n->count();//取出数据的总条数
        $page = new HomelibsPage($shuliang,15);//将page文件类引入。()里面需要参数,第一个参数是数据的总数量,第二个是每页显示多少条数据。所以上面要先求出数量。
        
        $xinxi = $page->fpage();        
        
        $attr = $n->limit($page->limit)->select();//查询出所有数据,limit(0,15),需要修改Page.class.php文件中的第57行$this->limit = "LIMIT ".$this->setLimit();,将 "LIMIT ".去掉,如果不去掉的话,将会显示limit(limit(0,15)),度了1个limit。
        $this->assign("shuju",$attr);//将查询出的数据都注入显示页面
        $this->assign("xinxi",$xinxi);
        $this->show();//调用显示方法在显示页面显示。
    }

2. Make the display page

<body>
<table width="100%" border="1" cellpadding="0" cellspacing="0">
    <tr>
        <td>代号</td>
        <td>名称</td>
        <td>父级代号</td>
    </tr>
    <foreach name="shuju" item="v" >
     <tr>
        <td>{$v.areacode}</td>
        <td>{$v.areaname}</td>
        <td>{$v.parentareacode}</td>
    </tr>
    </foreach>
</table>
<div>{$xinxi}</div><!--显示分页信息-->
</body>

3. What needs to be changed in Page.class.php

(1) The file name originally was page.class.php and needs to be changed to Page.class.php, which must be consistent with the class name;

(2) Copy Page.class.php to inside thinkphpApplicationHomelibs;

(3) namespace Homelibs; plus namespace.

(4) Modify line 57 in the Page.class.php file $this->limit = "LIMIT ".$this->setLimit(); and remove "LIMIT ".

5. The length of the output string

1. The encapsulation method is written in the same controller

public function test()
    {
        $str = "volist标签通常用于查询数据集(select方法)的结果输出,通常模型的select方法返回的结果是一个二维数组,可以直接使用volist标签进行输出。在控制器中首先对模版赋值:";//给str一个字符串
        $m = A("Main");//造一个Main控制器的对象
        echo $m->ChangDu($str);//输出$str的长度
    }
    
    public function ChangDu($str)//ChangDu方法,输出字符串的长度。
    {
        return strlen($str);
    }

2. The encapsulation method is not in the same controller In a controller

(1) Write only the following method in Maincontroller.class.php

public function test()
    {
        $str = "volist标签通常用于查询数据集(select方法)的结果输出,通常模型的select方法返回的结果是一个二维数组,可以直接使用volist标签进行输出。在控制器中首先对模版赋值:";//给str一个字符串
        $m = A("Main");//造一个Main控制器的对象
        echo ChangDu($str);//输出$str的长度
    }

(2) Write the encapsulated method functions.php in thinkphpApplicationHome, the content is as follows

<?php
function ChangDu($str)
{
    return strlen($str);
}
?>

(3) After writing this, enter http://localhost/thinkphp/index.php/Home/Main/test in the browser and you cannot read the length of the string. You also need to add it to the configuration file. The previous code:

"LOAD_EXT_FILE"=>"functions",//Automatically load the function library class

The length of the string can only be read after this code.

6. Automatically determine whether the session exists

1. Purpose of session

(1) Used to store user name and other information;

(2) Prevent skipping login;

2. If you follow the previous method, you must determine whether the session exists in each page or method.

(1) Create a Fucontroller class to determine whether the session exists.

<?php
namespace HomeController;
use ThinkController;
class FuController extends Controller//造一个FuController类,用来判断session值是否存在。
{
    public function __construct()//造一个构造函数
    {
        if(session(&#39;?uid&#39;))//判断session是否存在,如果存在,什么也不做。
        {
            
        }
        else//如果不存在
        {
            //$url = U("Home/Login/login");
            $this->redirect("Home/Login/login",array(),5,&#39;请登录&#39;);//第一个参数是跳转的地址,第二个参数是要传的值,第三个参数是跳转的时间,第四个参数是跳转时的提示信息。
            exit;
        }
    }
}
?>

(2) Write a test method. Note that the inherited parent class is FuController, not Controller. The first time you visit this page, you will jump to the login method. Because there is no session value, the above $this->redirect("Home/Login/login",array(),5,'Please log in') will be executed. ;

(3) Write a login method. The above test method will save the session after jumping to the login method, and then go to the test method and the length of the string will appear. Because of the session value, the test method will continue to execute.

<?php
namespace HomeController;
use ThinkController;
class LoginController extends Controller
{
    public function login()
    {
        session("uid","zhangsan");//存一个session值
    }
}
?>

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of Do you use ajax method in thinkphp?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn