wp_send_json()发送一个JSON相应到AJAX请求

目录

描述

Send a JSON response back to an AJAX request, and die().

wp_send_json() 描述

用法

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */
<?php wp_send_json( $response ) ?>

wp_send_json() 用法

参数

$response

(mixed) (必填) Variable (usually an array or object) to encode as JSON, then print and die.

默认值: None

wp_send_json() 参数

示例

/* ----------------------------------
 * 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 + " ID:" + data.ID);
                //This will alert "Saved ID:1"
            });
    });

});

save_field.php

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

<?php
//bootstrap WP

$nonce=$_POST['_wpnonce_name'];
if (empty($_POST) || !wp_verify_nonce($nonce, 'my-nonce') ) die('Security check');

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

wp_send_json($return);

Default Usage

wp_send_json() 示例

历史

  • 添加于 版本: 3.5.0

wp_send_json() 历史

源文件

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

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */
/**
 * Send a JSON response back to an Ajax request.
 *
 * @since 3.5.0
 *
 * @param mixed $response Variable (usually an array or object) to encode as JSON,
 *                        then print and die.
 */
function wp_send_json( $response ) {
	@header( 'Content-Type: application/json; charset=' . get_option( 'blog_charset' ) );
	echo wp_json_encode( $response );
	if ( defined( 'DOING_AJAX' ) && DOING_AJAX )
		wp_die();
	else
		die;
}

wp_send_json() 源文件