[wp-trac] [WordPress Trac] #28523: wp_send_json to allow for JSONP

WordPress Trac noreply at wordpress.org
Thu Jun 12 23:36:31 UTC 2014


#28523: wp_send_json to allow for JSONP
-------------------------+-----------------------------
 Reporter:  sc0ttkclark  |      Owner:
     Type:  enhancement  |     Status:  new
 Priority:  normal       |  Milestone:  Awaiting Review
Component:  General      |    Version:  3.5
 Severity:  normal       |   Keywords:
  Focuses:               |
-------------------------+-----------------------------
 {{{
 // Current
 function wp_send_json( $response ) {
 function wp_send_json_success( $data = null ) {
 function wp_send_json_error( $data = null ) {

 // Proposed
 function wp_send_json( $response, $callback = null ) {
 function wp_send_json_success( $data = null, $callback = null ) {
 function wp_send_json_error( $data = null, $callback = null ) {
 }}}

 The wp_send_jsonp and related functions could take another second
 parameter for $callback. It could default to null and if !== null then it
 could output the JSON in a JSONP compatible way:

 {{{
 if ( null !== $callback ) {
         @header( 'Content-Type: application/javascript; charset=' .
 get_option( 'blog_charset' ) );
         echo esc_js( $callback ) . '(' . json_encode( $response ) . ')';
 }
 else {
         @header( 'Content-Type: application/json; charset=' . get_option(
 'blog_charset' ) );
         echo json_encode( $response );
 }
 }}}

 The related functions would also get a second parameter for $callback in
 them, which would default to null and pass directly into wp_send_json:

 {{{
 $callback = 'my_js_callback'; // This can alternatively come from the
 $.ajax request 'callback' parameter

 if ( is_wp_error( $response ) ) {
         wp_send_json_error( $response->get_error_message(), $callback );
 }
 else {
         wp_send_json_error( $response, $callback );
 }
 }}}

 This is handy for when using $.ajax to make JSONP requests. Currently,
 wp_send_json won't work with JSONP requests, but the solution as outlined
 above would cause no bugs or impact beyond a parameter being added and the
 two alternate lines above.

--
Ticket URL: <https://core.trac.wordpress.org/ticket/28523>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform


More information about the wp-trac mailing list