Home  >  Article  >  PHP Framework  >  Let’s talk about how to use the JSON method in thinkphp5

Let’s talk about how to use the JSON method in thinkphp5

PHPz
PHPzOriginal
2023-04-07 09:24:592127browse

With the popularity of Web applications, the use of AJAX technology is becoming more and more widespread. JSON (JavaScript Object Notation) is a popular data format when dealing with front-end and back-end data interaction. In the ThinkPHP5 framework, JSON operations are very simple. This article will introduce how to use the JSON method in ThinkPHP5.

  1. Introduction to Json operations

In PHP, to convert an array into JSON format data, you only need to use the json_encode function.

$data = array('a' => 1, 'b' => 2, 'c' => 3);
echo json_encode($data); // {"a":1,"b":2,"c":3}

The json_decode function can be used to convert JSON format data into an array:

$json_data = '{"a":1,"b":2,"c":3}';
$data = json_decode($json_data, true);
print_r($data); // Array ( [a] => 1 [b] => 2 [c] => 3 )

In the ThinkPHP5 framework, JSON operations are simpler. The framework provides the Json class, which can easily process JSON data. , this class is located in think\response\Json.php.

  1. Json class usage

The Json class inherits from the Response class. The Response class is an abstract parent class of the response class. Its main function is to return the response to the client. . The main function of the Json class is to return data to the client in JSON format.

We can create a Json instance in the following way:

use think\response\Json;

$data = array('a' => 1, 'b' => 2, 'c' => 3);
$json = new Json($data);

Or create it in the following way:

$json = json($data);
  1. Json method introduction

The Json class provides multiple methods for processing JSON data. Let’s introduce them respectively below.

(1)data method

The data method is used to set the data to be returned.

$json = new Json();
$json->data($data);

Or:

$json->data($data)->code(200)->header(['Cache-control' => 'no-cache,must-revalidate'])->send();

(2) content method

The content method is used to set the type of data to be returned, such as the Content-Type type of application/json.

$json = new Json();
$json->content('application/json');

(3) jsonp method

jsonp method is used to generate JSONP data. It accepts two parameters. The first parameter is the name of the callback function, and the second parameter is the value to be returned. data.

$json = new Json();
$json->jsonp('callback', $data);

(4) code method

The code method is used to set the status code of the response. For example, 200 means the response is successful, 404 means the requested resource does not exist, etc.

$json = new Json();
$json->code(200);

(5) header method

The header method is used to set response header information.

$json = new Json();
$json->header(['Cache-control' => 'no-cache,must-revalidate']);

(6) options method

options method is used to set response options.

$json = new Json();
$json->options(['json_encode_param' => JSON_UNESCAPED_UNICODE]);

(7) send method

The send method is used to send response data.

$json = new Json($data);
$json->send();
  1. Json Example

Let’s learn how to use the Json class through an example. Suppose we need a JSON API to return a list of products. Each product has two attributes: ID and name.

First is the front-end code:

$.ajax({
    url: '/goods/list',
    dataType: 'jsonp',
    jsonp: 'callback',
    success: function(data) {
        if (data.code == 200) {
            $.each(data.data, function(index, item) {
                $('#goods-list').append('<li>' + item.id + ': ' + item.name + '</li>');
            });
        } else {
            alert('加载商品列表失败:' + data.msg);
        }
    },
    error: function(jqXHR, textStatus, errorThrown) {
        alert('加载商品列表失败:' + textStatus);
    }
});

Then add a list function in the controller Goods:

namespace app\index\controller;

use think\response\Json;

class Goods
{
    public function list()
    {
        // 模拟商品数据
        $goods_list = array(
            array('id' => 1, 'name' => '商品1'),
            array('id' => 2, 'name' => '商品2'),
            array('id' => 3, 'name' => '商品3'),
        );

        // 返回JSON数据
        $json = json($goods_list);
        $jsonp_callback = input('get.callback');
        if (!empty($jsonp_callback)) {
            $json->jsonp($jsonp_callback);
        }
        return $json;
    }
}

Finally, add a rule in the routing:

Route::get('/goods/list', 'index/Goods/list');

Run the program and access the path /goods/list to see the returned JSON data.

This article only introduces some basic usage methods of the Json class in the ThinkPHP5 framework. There are more advanced usages that readers need to explore on their own. I hope this article can provide some reference for everyone to understand the JSON operation of the ThinkPHP5 framework.

The above is the detailed content of Let’s talk about how to use the JSON method in thinkphp5. 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