Do you use ajax method in thinkphp?
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.

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='"+data[a].code+"'>"+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['status'] = 1; $data['content'] = 'content'; $this->ajaxReturn($data,'xml');
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('?uid'))//判断session是否存在,如果存在,什么也不做。
{
}
else//如果不存在
{
//$url = U("Home/Login/login");
$this->redirect("Home/Login/login",array(),5,'请登录');//第一个参数是跳转的地址,第二个参数是要传的值,第三个参数是跳转的时间,第四个参数是跳转时的提示信息。
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!
Hot AI Tools
Undresser.AI Undress
AI-powered app for creating realistic nude photos
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undress AI Tool
Undress images for free
Clothoff.io
AI clothes remover
Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!
Hot Article
Hot Tools
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
1386
52
How to run thinkphp project
Apr 09, 2024 pm 05:33 PM
To run the ThinkPHP project, you need to: install Composer; use Composer to create the project; enter the project directory and execute php bin/console serve; visit http://localhost:8000 to view the welcome page.
There are several versions of thinkphp
Apr 09, 2024 pm 06:09 PM
ThinkPHP has multiple versions designed for different PHP versions. Major versions include 3.2, 5.0, 5.1, and 6.0, while minor versions are used to fix bugs and provide new features. The latest stable version is ThinkPHP 6.0.16. When choosing a version, consider the PHP version, feature requirements, and community support. It is recommended to use the latest stable version for best performance and support.
How to run thinkphp
Apr 09, 2024 pm 05:39 PM
Steps to run ThinkPHP Framework locally: Download and unzip ThinkPHP Framework to a local directory. Create a virtual host (optional) pointing to the ThinkPHP root directory. Configure database connection parameters. Start the web server. Initialize the ThinkPHP application. Access the ThinkPHP application URL and run it.
Development suggestions: How to use the ThinkPHP framework to implement asynchronous tasks
Nov 22, 2023 pm 12:01 PM
"Development Suggestions: How to Use the ThinkPHP Framework to Implement Asynchronous Tasks" With the rapid development of Internet technology, Web applications have increasingly higher requirements for handling a large number of concurrent requests and complex business logic. In order to improve system performance and user experience, developers often consider using asynchronous tasks to perform some time-consuming operations, such as sending emails, processing file uploads, generating reports, etc. In the field of PHP, the ThinkPHP framework, as a popular development framework, provides some convenient ways to implement asynchronous tasks.
Which one is better, laravel or thinkphp?
Apr 09, 2024 pm 03:18 PM
Performance comparison of Laravel and ThinkPHP frameworks: ThinkPHP generally performs better than Laravel, focusing on optimization and caching. Laravel performs well, but for complex applications, ThinkPHP may be a better fit.
How to install thinkphp
Apr 09, 2024 pm 05:42 PM
ThinkPHP installation steps: Prepare PHP, Composer, and MySQL environments. Create projects using Composer. Install the ThinkPHP framework and dependencies. Configure database connection. Generate application code. Launch the application and visit http://localhost:8000.
How is the performance of thinkphp?
Apr 09, 2024 pm 05:24 PM
ThinkPHP is a high-performance PHP framework with advantages such as caching mechanism, code optimization, parallel processing and database optimization. Official performance tests show that it can handle more than 10,000 requests per second and is widely used in large-scale websites and enterprise systems such as JD.com and Ctrip in actual applications.
Development suggestions: How to use the ThinkPHP framework for API development
Nov 22, 2023 pm 05:18 PM
Development suggestions: How to use the ThinkPHP framework for API development. With the continuous development of the Internet, the importance of API (Application Programming Interface) has become increasingly prominent. API is a bridge for communication between different applications. It can realize data sharing, function calling and other operations, and provides developers with a relatively simple and fast development method. As an excellent PHP development framework, the ThinkPHP framework is efficient, scalable and easy to use.


