我正在尝试从自定义字段值(嵌入)加载视频<iframe>
). 单击任意按钮并播放该视频。
Console log: 当我单击任何按钮时,它将转到jquery行console.log(result);
. 不提供与按钮相关的输出。
What missing and how to make it working-able?
HTML:
<ul>
<li><button class="play_next" data-meta-key="url-1">Video 1</button></li>
<li><button class="play_next" data-meta-key="url-2">Video 2</button></li>
<li><button class="play_next" data-meta-key="url-3">Video 3</button></li>
</ul>
Jquery:
jQuery( document ).ready( function( $ ) {
$( \'.play_next\' ).on(\'click\', function( event ) {
event.preventDefault();
var meta_key = $( this ).data( \'metaKey\' );
var post_id = $( this ).data( \'post_id\' );
$.ajax( {
url: ajaxobject.ajaxurl,
type: \'get\',
dataType: \'html\',
data: {
action: \'wpse_296903_call_meta\',
meta_key: meta_key,
post_id: post_id,
},
success: function( result) {
$( \'#output\' ).append( result );
console.log(result);
}
});
});
});
PHP:
function wpse_296903_call_meta() {
if( isset( $_POST[\'post_id\'] ) && isset( $_POST[\'meta_key\'] )) {
$post_id = $_POST[\'post_id\'];
$meta_key = $_POST[\'meta_key\'];
if ( in_array( $meta_key, [\'url-1\', \'url-2\', \'url-3\'] ) ) {
echo get_post_meta( $post_id, $meta_key, true );
}
}
wp_die();
}
add_action( \'wp_ajax_wpse_296903_call_meta\', \'wpse_296903_call_meta\' );
add_action( \'wp_ajax_nopriv_wpse_296903_call_meta\', \'wpse_296903_call_meta\' );
Enqueue_script:
if ( ! function_exists( \'cf_enqueue_scripts\' ) ) :
function cf_enqueue_scripts() {
wp_deregister_script( \'jquery\' );
wp_enqueue_script( \'jquery\', get_template_directory_uri() . \'/js/jquery.min.js\');
wp_deregister_style( \'style\' );
wp_enqueue_style( \'style\', get_bloginfo(\'stylesheet_url\'));
wp_enqueue_script( \'script\', get_template_directory_uri() . \'/js/ajax.js\');
wp_localize_script(\'script\', \'ajaxobject\', array(
\'ajaxurl\' => admin_url(\'admin-ajax.php\')
));
}
add_action( \'wp_enqueue_scripts\', \'cf_enqueue_scripts\' );
最合适的回答,由SO网友:maheshwaghmare 整理而成
添加数据属性data-post-id
对于职位id,例如
HTML:
<ul>
<li><button class="play_next" data-meta-key="url-1" data-post-id="<?php the_ID(); ?>">Video 1</button></li>
...
</ul>
js中缺少数据属性。
$( this ).data( \'metaKey\' );
应该是
$( this ).data( \'meta-key\' );
和
$( this ).data( \'post_id\' );
应该是
$( this ).data( \'post-id\' );
E、 g.
Jquery:
jQuery( document ).ready( function( $ ) {
$( \'.play_next\' ).on(\'click\', function( event ) {
event.preventDefault();
var meta_key = $( this ).data( \'meta-key\' );
var post_id = $( this ).data( \'post-id\' );
...
});
});
使用
$_GET
或
$_REQUEST
而不是
$_POST
E、 g.
PHP:
function wpse_296903_call_meta() {
if( isset( $_GET[\'post_id\'] ) && isset( $_GET[\'meta_key\'] )) {
$post_id = $_GET[\'post_id\'];
$meta_key = $_GET[\'meta_key\'];
...
}
wp_die();
}
Additional Notes
<使用Ajax时添加nonce清洗输入