在一個不支持PHP的主機上,須要對某些頁面作訪問統計。個人方案是在靜態的HTML頁面上,用JSONP向可以執行PHP的主機進行跨域請求,從而使用PHP解決這個訪問量統計問題。javascript
在服務器端,PHP頁面返回的JSONP格式應該是這樣的:php
<?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發起請求的代碼能夠參考下面: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>
通用方法:java
// 初始化數據,同一個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); }) } }) }
大概就這樣,使用起來也是很簡單的。jquery
下面再介紹PHP經常使用的方法,將數組轉換爲JSONP格式的輸出:ajax
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.phpjson