wp_send_json_error()发送带有失败标记的JSON数据给Ajax请求

目录

描述

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

wp_send_json_error() 描述

用法

<?php wp_send_json_error$data );

// What the response will look like before it is encoded.
$response = array( 'success' => false ); //if $data is empty
$response = array( 'success' => false'data' => $data ); //if $data is set
?>

wp_send_json_error() 用法

参数

$data

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

默认值: null

wp_send_json_error() 参数

示例

/* ----------------------------------
 * 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.success);                
            });
    });

});

save_field.php

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

<?php
$nonce=$_POST['_wpnonce_name'];
if (empty($_POST) || !wp_verify_nonce($nonce, 'my-nonce') )
	wp_send_json_error(); // sends json_encoded success=false

wp_send_json_error() 示例

注意

使用到 wp_send_json() to send response.

wp_send_json_error() 注意

历史

  • 添加于 版本: 3.5.0

wp_send_json_error() 历史

源文件

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

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */
/**
 * Send a JSON response back to an Ajax request, indicating failure.
 *
 * If the `$data` parameter is a {@see WP_Error} object, the errors
 * within the object are processed and output as an array of error
 * codes and corresponding messages. All other types are output
 * without further processing.
 *
 * @since 3.5.0
 * @since 4.1.0 The `$data` parameter is now processed if a {@see WP_Error}
 *              object is passed in.
 *
 * @param mixed $data Data to encode as JSON, then print and die.
 */
function wp_send_json_error( $data = null ) {
	$response = array( 'success' => false );

	if ( isset( $data ) ) {
		if ( is_wp_error( $data ) ) {
			$result = array();
			foreach ( $data->errors as $code => $messages ) {
				foreach ( $messages as $message ) {
					$result[] = array( 'code' => $code, 'message' => $message );
				}
			}

			$response['data'] = $result;
		} else {
			$response['data'] = $data;
		}
	}

	wp_send_json( $response );
}

wp_send_json_error() 源文件