我是ajax的新手,我正在尝试创建一个简单的命中计数器,在页面加载后更新Wordpress中的自定义字段。页面被缓存,因此任何单独使用PHP的尝试都不会起作用。
我只想通过ajax将帖子ID传递给php文件,获取定制字段,并用新的点击次数更新它。
我目前有以下代码,但无法获取它来更新自定义域。下面是jquery:
$(document).ready(function(
$.ajax({
url:'http://www.example.com/hits/hits.php',
cache: false,
type: 'POST',
data: {PostId: '<?php echo get_the_ID() ?>'}
});
));以及它所调用的PHP文件:
<?php
/* Template Name: AJAX */
?>
<?php
$postid = $_POST['PostId']; // get the hits from AJAX and save it for PHP
$hits = (int) get_post_meta($postid, 'hit_number', true);
$newhits = $hits + 1;
update_post_meta($postid, 'hit_number', $newhits);
?>我做错了什么?另外,有没有办法将PHP函数包含在相同的页面/文件中,以避免引入外部文件?我担心随着流量变大,文件会被请求得太频繁。
谢谢你的帮忙!
发布于 2013-06-13 23:23:03
在查询字符串中添加时间戳。
var date = new Date();
var timestamp = date.getTime();
$(document).ready(function(
$.ajax({
url:'http://www.example.com/hits/hits.php?t=' + timestamp,
cache: false,
type: 'POST',
data: {PostId: '<?php echo get_the_ID() ?>'}
});
));在查询字符串中添加时间戳的目的是为了避免获取缓存的结果。
https://stackoverflow.com/questions/17090884
复制相似问题