在一个不支持PHP的主机上,需要对某些页面做访问统计。我的方案是在静态的HTML页面上,用JSONP向能够执行PHP的主机进行跨域请求,从而使用PHP解决这个访问量统计问题。
在服务器端,PHP页面返回的JSONP格式应该是这样的:
<?php
echo $_GET["callback"].'
(
{
title: "The Principles of Beautiful Web Design, 2nd Edition",
url: "http://www.sitepoint.com/books/design2/",
author: "Jason Beaird",
publisher: "SitePoint",
price: {
currency: "USD",
amount: 39.95
}
}
);
'
?>
而静态HTML发起请求的代码可以参考下面:
<script language="javascript" src="http://www.nowamagic.net/zt/access_count/js/jquery-1.4.2.min.js"></script> <script language="javascript" src="http://www.nowamagic.net/zt/access_count/js/jquery.jsonp-2.1.4.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ insert_vote(); }) function insert_vote(){ var j = null; $.ajax({ type:'get', url:'http://www.nowamagic.net/zt/access_count/jsonp.php', dataType:'jsonp', jsonp:"callback", data:{"a":"insert", "type":"aa", "time":"bb", "id":"dd", "allowVote":"cc"}, async: false, success:function(data){ j = data; //alert("1"); alert(j.title); } }) } function init(){ $.ajax({ dataType: 'jsonp', data: 'id=10', jsonp: 'jsonp_callback', url: 'http://www.nowamagic.net/zt/access_count/jsonp.php', success: function () { // do stuff alert(jsonp.respond); }, }); } function init2(){ $.ajax({ async:false, url: 'http://www.nowamagic.net/zt/access_count/jsonp.php', // 跨域URL type: 'GET', dataType: 'jsonp', jsonp: 'jsoncallback', //默认callback data: 'id=10', //请求数据 timeout: 5000, beforeSend: function(){ //jsonp 方式此方法不被触发。原因可能是dataType如果指定为jsonp的话,就已经不是ajax事件了 }, success: function(json) { //客户端jquery预先定义好的callback函数,成功获取跨域服务器上的json数据后,会动态执行这个callback函数 alert(json.respond.title); if(json.actionErrors.length!=0) { alert(json.actionErrors); } }, complete: function(XMLHttpRequest, textStatus){ }, error: function(xhr){ //jsonp 方式此方法不被触发 //请求出错处理 alert("请求出错(请检查相关度网络状况.)"); } }); } </script>
通用方法:
// 初始化数据,同一个cookie一分钟的访问量都算一次
function init_count(pageType, id){
var j = null;
$.ajax({
type: "get", //使用get方法访问后台
dataType: "jsonp", //返回json格式的数据
jsonp:"callback",
url: "http://app2.zhnews.net/zt/access_count/manage.php", //要访问的后台地址
data:{"opp":"main", "pageType":pageType, "id":id},
async: false,
success: function(data){
//alert(data.total);
//$('#pc_1').html(msg.total);
$.each(data, function(i, v){
var tmp = v.record.split(":");
var month_view = tmp[tmp.length - 1];
$("label[id=pc_"+v.page_id+"]").html(v.total);
$("label[id=pcm_"+v.page_id+"]").html(v.week);
})
}
})
}
大概就这样,使用起来也是很简单的。
下面再介绍PHP常用的方法,将数组转换为JSONP格式的输出:
function arrayRecursive(&$array, $function, $apply_to_keys_also = false)
{
static $recursive_counter = 0;
if (++$recursive_counter > 1000) {
die('possible deep recursion attack');
}
foreach ($array as $key => $value) {
if (is_array($value)) {
arrayRecursive($array[$key], $function, $apply_to_keys_also);
} else {
$array[$key] = $function($value);
}
if ($apply_to_keys_also && is_string($key)) {
$new_key = $function($key);
if ($new_key != $key) {
$array[$new_key] = $array[$key];
unset($array[$key]);
}
}
}
$recursive_counter--;
}
function JSON($array) {
arrayRecursive($array, 'urlencode', true);
$json = json_encode($array);
return urldecode($json);
}
$array = array
(
'total' => $total,
'current' => $current
);
echo $_GET["callback"].'('.JSON($array).')';
原文地址:http://www.nowamagic.net/jquery/jquery_JsonpUseMark.php