我的帖子中有一个iframe(我正在嵌入YouTube视频)。php模板。我需要做的是,每当iframe被鼠标覆盖时,都会通过Ajax将一个值传递给一个自定义字段,以便存储视频被鼠标覆盖的次数。这是我的鼠标盖代码:
$("iframe").mouseover(function(){
<?php
global $post;
$id = $post->ID;
$dataString = \'pid=\' . $id;
?>
$.ajax({
type: "POST",
url: "<?php bloginfo(\'template_directory\'); ?>/ajax.php",
data: "<?php echo $dataString; ?>",
cache: false,
success: function(html) {
console.log(html);
}
});
});
代码的这一部分似乎工作正常。下面是ajax的代码。php
<?php
define( \'WP_USE_THEMES\', false );
require_once( \'../../../wp-load.php\' );
$pid = $_POST[\'pid\'];
$counter_value = get_post_meta( $pid, \'counter\' );
$counter_value = $counter_value + 1;
update_post_meta( $post_id = $pid, $key = \'counter\', $value = \'$counter_value\' );
echo ("success");
?>
问题似乎在于ajax。php未检测到$\\u POST[\'pid\']。也许这不是问题,我现在有点不知所措。如果有人有任何建议,我将不胜感激!
SO网友:Kev
问题是我的计数器值。它最初被设置为一个字符串,所以我将它转换为一个整数,一切都很好。
完成代码:
Page data being sent from
$("iframe").mouseover(function(){
<?php
global $post;
$id = $post->ID;
?>
$.ajax({
type: "POST",
url: "<?php bloginfo(\'template_directory\'); ?>/ajax.php",
data: "pid=<?php echo $id; ?>",
cache: false,
success: function(html) {
console.log(html);
}
});
});
On the Ajax processing page:
<?php
define( \'WP_USE_THEMES\', false );
require_once( \'../../../wp-load.php\' );
$pid = $_POST[\'pid\'];
$counter_val = get_post_meta( $pid, \'counter\', true );
$counter_val = floatval($counter_val);
$counter_val = $counter_val + 1;
echo $counter_val;
update_post_meta( $post_id = $pid, $key = \'counter\', $value = $counter_val );
echo "done";
?>