wp_send_json_success()发送带有成功标记的JSON数据给Ajax请求

目录

描述

Send a JSON response back to an Ajax request, indicating success. The response object will always have a success key with the value true. If anything is passed to the function it will be encoded as the value for a data key.

wp_send_json_success() 描述

用法

<?php wp_send_json_success$data );
$response = array( 'success' => true ); //if $data is empty
$response = array( 'success' => true'data' => $data ); //if $data is set ?>

wp_send_json_success() 用法

参数

$data

(mixed) (可选) Data to encode as JSON, then print and die.

默认值: null

wp_send_json_success() 参数

示例

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */
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

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */

<?php
// bootstrap WP

$return = array(
			'message'	=> 'Saved',
			'ID'		=> 1
	);

wp_send_json_success($return);

wp_send_json_success() 示例

注意

使用到 wp_send_json() to send response.

wp_send_json_success() 注意

历史

  • 添加于 版本: 3.5.0

wp_send_json_success() 历史

源文件

wp_send_json_success() 函数的代码位于 wp-includes/functions.php

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */
/**
 * Send a JSON response back to an Ajax request, indicating success.
 *
 * @since 3.5.0
 *
 * @param mixed $data Data to encode as JSON, then print and die.
 */
function wp_send_json_success( $data = null ) {
	$response = array( 'success' => true );

	if ( isset( $data ) )
		$response['data'] = $data;

	wp_send_json( $response );
}

wp_send_json_success() 源文件