首页 > 代码库 > jQuery-PHP跨域请求数据

jQuery-PHP跨域请求数据

jQuery:

 1 //获取域名
 2 function getDomain(url){
 3     var a = document.createElement(‘a‘);
 4     a.href =http://www.mamicode.com/ url;
 5     url=a.hostname;
 6     return url;
 7 }
 8 
 9 //记录访客
10 function recordVisitor(){
11     var referrerMz = escape(getDomain(document.referrer));
12     var hrefMz = escape(getDomain(window.location.href));
13     sendInfo="judgeMz=413322&referrerMz="+escape(referrerMz)+"&hrefMz="+escape(hrefMz);
14     $.ajax({ 
15         type: "get", 
16         async: true, 
17         url: "http://www.mazey.net/config/api/record-receive.php", 
18         data:{judgeMz:413322,referrerMz:referrerMz,hrefMz:hrefMz}, 
19         dataType: "jsonp", 
20         jsonp: "callback",
21         jsonpCallback:"returnFun",
22         success: function(data){ 
23             myArr=data.split("-|-")
24             if("0507"==myArr[0]){
25                 console.log(myArr[1]);
26             }else if("0215"==myArr[0]){
27                 console.log(myArr[1]);
28             }
29         }, 
30         error: function(){ 
31             console.log("Server Error!");
32         } 
33     });
34 }
35 
36 //加载
37 $(document).ready(function () { 
38     recordVisitor();
39 }); 

PHP:

 1 <?php
 2 require ‘../config.php‘;
 3 $judgeMz=$_GET["judgeMz"];//TODO 后续做一个验证不是413322的报错
 4 $referrerMz=$_GET["referrerMz"];
 5 $hrefMz=$_GET["hrefMz"];
 6 $visitorIP=getIP();
 7 
 8 $data = returnFun($referrerMz,$hrefMz,$visitorIP); 
 9 exit($_GET[‘callback‘] . ‘(‘ . json_encode($data) . ‘)‘); 
10 
11 function returnFun($referrerMz,$hrefMz,$visitorIP) { 
12     $urlRecordVisitor=‘http://www.mazey.cn/config/config-asp/api/record-receive.asp?referrerMz=‘.$referrerMz.‘&hrefMz=‘.$hrefMz.‘&visitorIP=‘.$visitorIP;
13     $resultMz = file_get_contents($urlRecordVisitor);
14     return $resultMz;
15 }
16 ?>

其他:

因为http://www.mazey.cn/config/config-asp/api/record-receive.asp在国内,所以访问起来好像有点慢。准备按照asp重写下php的后端写入代码,本来计划了不少事情,其他事情这一步做完以后再说吧。

jQuery-PHP跨域请求数据