我很难理解wp\\u send\\u json\\u error如何返回错误消息。只要不满足任何错误条件,它就可以正常工作。但如果出现错误,则不会返回任何内容。
如何返回中设置的错误消息wp_send_json_error()
何时出现错误?
查看我的代码:
function submit_youtube_callback() {
check_ajax_referer( \'randomnonce\', \'security\' );
if ( !isset($_POST[\'post_id\']) ||
!is_numeric($_POST[\'post_id\']) ||
!get_post_status($_POST[\'post_id\']) ||
!isset($_POST[\'yt_url\']) ||
!isset($_POST[\'terms\'])
) {
wp_send_json_error( \'Error: Invalid data!\' );
}
// Check if terms are checked
$terms = $_POST[\'terms\'];
if ( $terms != true ) {
wp_send_json_error( \'Error: You must accept the terms.\' );
}
// Check if valid youtube URL
$youtube_url = $_POST[\'yt_url\'];
$preg = \'~^(?:https?://)?(?:www\\.)?(?:youtube\\.com|youtu\\.be)/watch\\?v=([^&]+)~x\';
$has_match = preg_match($preg, $youtube_url, $matches);
if ( empty($matches[1]) ) {
wp_send_json_error( \'Error: You did not enter a valid YouTube URL.\');
}
echo \'<p>youtube: \'. $youtube_url .\'</p>\';
echo \'<p>terms accepted: \' . $terms .\'</p>\';
wp_die();
} add_action( \'wp_ajax_cp_narrations_callback\', \'submit_youtube_callback\' );
和Javascript:
function submit_youtube_javascript() {
if ( is_single() ) {
$ajax_nonce = wp_create_nonce( "randomnonce" );
?>
<script>
( function( $ ) {
var ajaxurl = "<?php echo admin_url(\'admin-ajax.php\'); ?>",
submit_youtube = $(\'#submitYouTubeForm\');
// Star rating button
$(submit_youtube).on(\'submit\', function(event) {
event.preventDefault();
var submit_youtube_url = $(\'#submitYouTubeURL\').val(),
submit_youtube_terms = $(\'#youtube_terms\').is(\':checked\');
// Data to be sent to function
var data = {
\'action\': \'submit_youtube_callback\',
\'security\': \'<?php echo $ajax_nonce; ?>\',
\'post_id\': <?php echo get_the_ID(); ?>,
\'yt_url\': submit_youtube_url,
\'terms\': submit_youtube_terms
};
// Send Data
jQuery.post(ajaxurl, data, function(response) {
submit_youtube.replaceWith(response);
});
});
} )( jQuery );
</script>
<?php
}
} add_action( \'wp_footer\', \'submit_youtube_javascript\', 100 );