当前浏览:首页 / WordPress函数 / wp_send_json()

wp_send_json( mixed $response, int $status_code = null, int $options )

将JSON响应发送回Ajax请求

json

send


参数

$response

(mixed)(必填) 变量(通常是数组或对象)编码为JSON,然后打印并die。

$status_code

(int)(可选) 要输出的HTTP状态代码。

默认值: null

$options

(int)(可选) 要传递给json_encode()的选项。默认值为0。



源码

查看源码 官方文档


更新日志

版本描述
5.6.0添加了$options参数。
4.7.0添加了$status_code参数。
3.5.0开始引入

使用示例

  • 示例1
    <?php
    // .................
    // nonce checks ....
    // .................
    
    $return = array(
        'message'  => 'Saved',
        'ID'       => 1
    );
    
    wp_send_json($return);

    注意:使用wp_send_json()后不需要再使用wp_die()或exit(0),因为它会自动调用wp_die()。

  • 示例2

    如果这是一个REST响应(即通过RESTAPI),则使用WP_REST_ResponseWP_Error