Home  >  Article  >  PHP Framework  >  How js interacts with thinkphp5 data

How js interacts with thinkphp5 data

WBOY
WBOYOriginal
2023-05-28 22:24:361243browse

In recent years, the rapid development of front-end technology has provided better possibilities for the development model of front-end and back-end separation. In development, JavaScript (JS for short), as a commonly used front-end development language, has also become an indispensable part of front-end development. In this case, how JS interacts with the back-end framework php5 (TP5 for short) has become one of the issues that developers are concerned about. In this article, I will introduce the data interaction method between JS and tp5 in detail from several aspects.

1. Front-end and back-end data interaction methods

There are usually two ways of front-end and back-end data interaction: synchronous and asynchronous. The synchronous method means that after the front-end sends a request, it has to wait for the back-end to return data before responding; the asynchronous method does not need to wait. After the front-end initiates the request, it can continue to execute downwards and wait for the back-end data to return before processing.

In actual development, the synchronization method has become less and less used due to its shortcomings such as lagging. The asynchronous method has become the main method for front-end and back-end data interaction. In the following discussion, we will mainly explain the method of interacting between JS and tp5 data in asynchronous mode.

2. Use ajax to realize asynchronous communication

In asynchronous communication, the core is to use ajax to realize front-end and back-end data communication. Ajax is the abbreviation of Asynchronous JavaScript and XML (asynchronous JavaScript and XML). It is an asynchronous communication technology using JavaScript. It can update parts of a page without reloading the entire page.

When using ajax, we need to write JS code in the front-end part and tp5 code in the back-end part. After the front end sends an ajax request, the back end will return Json data (it can also be data in XML format) after receiving the request. After the data is returned, it is processed by the front-end JS.

The following is a case in actual development. On this basis, the specific implementation of asynchronous interaction between JS and tp5 is introduced in detail.

Step one: Write front-end code on the front-end

We first write a page to set user permissions on the front-end. The page needs to implement two operations: adding and deleting permissions. Here, we take the "add" operation as an example to illustrate.

We first need to write a button on the page so that after clicking the button, a form filling in the permission information will appear. At the same time, in order to conveniently display permission information, we also need to write a table on the page to display all permission information.

Use the following JS code to generate an HTML table to display permission information.

function getAuthorityTable() {
    $.ajax({
        type: "GET",
        url: "/index/getAuthorityTable",
        dataType: "json",
        success: function (data) {
            var table = "<table><thead><tr><th>权限编号</th><th>权限名</th><th>操作</th></thead><tbody>";
            for (var i = 0; i < data.length; i++) {
                table += "<tr><td>" + data[i]["id"] + "</td><td>" + data[i]["authority_name"] + "</td><td><button onclick='deleteAuthority(" + data[i]["id"] + ")'>删除</button></td></tr>";
            }
            table += "</tbody></table>";
            $("#authorityTable").html(table);
        }
    });
}

Here we use ajax to asynchronously obtain back-end data and generate an HTML table consisting of three parts: permission number, permission name, and deletion operation. Among them, the getAuthorityTable() method defines the front-end request URL and generates an HTML table from the request results to display on the page.

Step 2: Write tp5 code on the backend

We need to write a method on the server side to respond to the URL request. In tp5, we can use controllers and models to implement.

For example, we can add a setAuthority method in the controller Index controller:

public function setAuthority()
{
    $authority_name = input('post.authority_name');
    $model = new Authority();
    if ($model -> add_authority($authority_name)) {
        $this -> success('添加权限成功!');
    } else {
        $this -> error('添加权限失败!');
    }
}

In the above code, we use the input method to receive the POST parameters and call the add_authority method in the Authority model class Add permission information. Finally, the built-in $this->success and $this->error methods of tp5 are used to return status information to inform the front-end of the success or failure of the operation.

Step 3: Use JS to send a request on the front end

We need to implement in the front-end JS code, after clicking the button, send a request to the backend and obtain the response returned by the backend.

Take the adding permission operation as an example, and implement this operation in the button click event.

function addAuthority() {
    var authority_name = $("#authorityName").val();
    $.ajax({
        type: "POST",
        url: "/index/setAuthority",
        dataType: "json",
        data: {authority_name: authority_name},
        success: function (data) {
            alert(data.msg);
        }
    });
}

In the above code, we use the POST method to send a request to the server, sending "authority_name" as a parameter to the SetAuthority controller. Next, data.msg is used to return the operation status information.

3. Other matters needing attention

In addition to the above, there are some points that need attention:

1. Cross-domain request: Since the ajax request is asynchronous, and the domain name They are front-end and back-end respectively. In order to ensure security, the front-end JS and the back-end server are not under the same domain name. At this time, you need to consider solving the problem of cross-domain requests. Common solutions include using JSONP, adding Header in the backend, etc.

2.CSRF attack: Since ajax asynchronous requests can lead to cross-site request forgery (CSRF) security issues, tp5 has used its own method to prevent CSRF attacks, which can be modified in the thinkconfig.php file during development. Related parameters.

3. Front-end and back-end interaction verification: In order to ensure the security of the system, verification is required during the front-end and back-end data interaction process. You can use the tp5 Validator class to perform related operations.

4.JSON data processing: Since JSON format data needs to be processed during asynchronous ajax requests, front-end JS often uses Json.stringify, JSON.parse and other methods to perform related operations.

In short, the data interaction between JS and tp5 is implemented based on the asynchronous communication method of ajax. As long as we understand the communication methods of JS and tp5 and learn the corresponding tools and methods, we can complete website development more efficiently. At the same time, during the development process, we also need to consider some security and verification issues. I hope this article can be helpful to readers.

The above is the detailed content of How js interacts with thinkphp5 data. 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