Introduce wp_send_json() to json-encode a variable, print it, and die, for Ajax requests. Effectively replaces WP_Ajax_Response, which was an XML-based response.

Introduce wp_send_json_success() and wp_send_json_error(), which will allow us to fire appropriate done() or fail() callbacks in JS.

props koopersmith. see #21390.



git-svn-id: http://core.svn.wordpress.org/trunk@21679 1a063a9b-81f0-0310-95a4-ce76da25c4cd
This commit is contained in:
Andrew Nacin 2012-08-31 01:56:00 +00:00
parent e286612fda
commit c8a328f100
1 changed files with 50 additions and 2 deletions

View File

@ -1799,7 +1799,7 @@ function wp_get_mime_types() {
'mid|midi' => 'audio/midi', 'mid|midi' => 'audio/midi',
'wma' => 'audio/wma', 'wma' => 'audio/wma',
'mka' => 'audio/x-matroska', 'mka' => 'audio/x-matroska',
// Misc application formats // Misc application formats
'rtf' => 'application/rtf', 'rtf' => 'application/rtf',
'js' => 'application/javascript', 'js' => 'application/javascript',
'pdf' => 'application/pdf', 'pdf' => 'application/pdf',
@ -1857,7 +1857,7 @@ function wp_get_mime_types() {
* *
* @uses apply_filters() Calls 'upload_mimes' on returned array * @uses apply_filters() Calls 'upload_mimes' on returned array
* @uses wp_get_upload_mime_types() to fetch the list of mime types * @uses wp_get_upload_mime_types() to fetch the list of mime types
* *
* @return array Array of mime types keyed by the file extension regex corresponding to those types. * @return array Array of mime types keyed by the file extension regex corresponding to those types.
*/ */
function get_allowed_mime_types() { function get_allowed_mime_types() {
@ -2142,6 +2142,54 @@ function _scalar_wp_die_handler( $message = '' ) {
die(); die();
} }
/**
* 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 json_encode( $json );
if ( defined( 'DOING_AJAX' ) && DOING_AJAX )
wp_die();
else
die;
}
/**
* 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 );
}
/**
* Send a JSON response back to an Ajax request, indicating failure.
*
* @since 3.5.0
*
* @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 ) )
$response['data'] = $data;
wp_send_json( $response );
}
/** /**
* Retrieve the WordPress home page URL. * Retrieve the WordPress home page URL.
* *