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

wp_send_json_success( mixed $data = null, int $status_code = null, int $options )

将JSON响应发送回Ajax请求,表示成功

json

send


参数

$data

(mixed)(可选) 将数据编码为JSON,然后打印并die。

默认值: null

$status_code

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

默认值: null

$options

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


更多信息

响应对象将始终具有值为truesuccess键。如果向函数传递了任何内容,它将被编码为data键的值。

将以下示例数组转换为JSON:

$response = array( 'success' => true );                   //if $data is empty
$response = array( 'success' => true, 'data' => $data );  //if $data is set


源码

查看源码 官方文档


更新日志

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

使用示例

  • 示例1

    将JSON请求发送回Zapier,下面是一个帮助人们入门的示例。您可以发送获取返回/显示所需的任何数据的关联数组。

    wp_send_json_success( array( 
        'name' => 'Andrew', 
        'call' => 'From some API/trigger', 
        'variable' => $var,
    ), 200 );
    
  • 示例2

    基本示例

    jQuery( document ).ready( function() {
    
    	jQuery( '#btn_save' ).click( function( e ) {
    		e.preventDefault();
    		jQuery.post( pluginUrl+ 'ajax/save_field.php', 
    			jQuery( '#my-form' ).serialize(), function( data ) {                        
    				alert( data.message ); 
    			}
    		);
    	} );
    } );
    

    save_field.php:

    // Bootstrap WP
    
    $return = array(
    	'message' => __( 'Saved', 'textdomain' ),
    	'ID'      => 1
    );
    wp_send_json_success( $return );