我有一个正在开发的 WordPress 插件,它可以对所有主要的社交网站进行投票,并返回特定用户的社交人数(关注者)。
这在服务器上可能会非常缓慢和密集,因此我使用 WordPress 瞬态缓存构建了插件来存储从社交网络站点返回的详细信息,并且还使用 jQuery AJAX json 来显示数据。
这些是主要功能:
检索 Facebook 计数
/**
* Fetch Facebook count.
*
* @param string $url The url to fetch.
* @return int of Facebook counts.
*/
function ass_get_fb_likes($facebook_id) {
try {
$json = wp_remote_get("http://graph.facebook.com/".$facebook_id);
if(is_wp_error($json))
return false;
$fbData = json_decode($json['body'], true);
return format(intval($fbData['likes']));
} catch (Exception $e) {
return false;
}
}
上面的这个函数也连接到另一个处理瞬态缓存的函数。这方面效果很好。
处理社交网络数据的初始显示
jQuery(function($) {
$('#fblikes').advanceddashboardwidget({
'action':'get_facebook_likes',
'service':'facebook',
'countof':'likes',
'callback':'formatCount'
});
});
格式化显示的辅助函数
function formatCount(element,count){
var display_count='';
count=parseInt(count,10);
if(count>1000000)
{
count=count/1000000;
count=count.toFixed(0);
display_count=count+'m';
}
else if(count>1000)
{
count=count/1000;
count=count.toFixed(0);
display_count=count+'k';
}
else
{
display_count=count;
}
element.html(display_count);
}
如果给我的问题,请使用以下功能。它用于与 WordPress 通信以调用 PHP 函数并检索数据。
(function($) {
$(document).ready( function() {
var AdvancedDashboardWidget = function(element, options)
{
var ele = $(element);
var settings = $.extend({
action: '',
service: '',
countof: '',
query: '',
callback:''
}, options || {});
this.count=0;
var url='';
switch(settings.service)
{
case 'facebook':
if(settings.countof=='likes' || settings.countof=='talks')
{
ajaxCall(action,ele,settings);
}
break;
}
};
var ajaxCall = function(action,ele,settings){
opts = {
url: ajaxurl, // ajaxurl is defined by WordPress and points to /wp-admin/admin-ajax.php
type: 'POST',
async: true,
cache: false,
dataType: 'json',
data:{
action: settings.action // Tell WordPress how to handle this ajax request
},
success:function(response) {
//alert(response);
ele.html(response);
return;
},
error: function(xhr,textStatus,e) { // This can be expanded to provide more information
alert(e);
//alert('There was an error deleting the cache');
return;
}
};
$.ajax(opts);
};
$.fn.advanceddashboardwidget = function(options)
{
return this.each(function()
{
var element = $(this);
// Return early if this element already has a plugin instance
if (element.data('advanceddashboardwidget')) return;
// pass options to plugin constructor
var advanceddashboardwidget = new AdvancedDashboardWidget(this, options);
// Store plugin object in this element's data
element.data('advanceddashboardwidget', advanceddashboardwidget);
});
};
});
})(jQuery);
问题
问题是,当从瞬态函数返回数据时,总是会在数字后面附加一个额外的 0(零)。从我一直在阅读的内容来看,这可能是因为我使用的是“ json
”而不是“ jsonp
”。
当我将其更改为“ jsonp
”时,出现错误“错误:未调用 jQuery172011280598581866697_1353705456268”。我想这与回调函数有关。
到目前为止,我发现这是在网站上显示此信息的最快方式。如果数据存在于瞬态缓存中,则页面加载速度很快,但如果不是,则可能需要几秒钟,这就是我希望 jQuery 进入的地方,并且可能会显示加载图形,直到检索到数据。
任何帮助将不胜感激。