微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php-使JQuery中的getJSON将cookie传递到外部域?

当我在JQuery中使用getJSON到外部域时,发出的请求不包含该域的cookie.我正在将其用于正在编写的分析脚本,并且需要在脚本运行所在的外部域上设置Cookie,以便跟踪唯一身份访问者.

文件

domain1.com/website.html

    <script src="http://domain2.com/tracker.js"></script>

domain2.com/tracker.js

//Get @R_105_4045@ion about the user
info = "(here's some things about the user)";

//Send data using JSON
$.getJSON("http://domain2.com/getdata.PHP?"+info,
            function(data){}
         );

domain2.com/getdata.PHP

 /******
  * Code to save data and stuff
  *******/

//Get the current cookie (if any).
$current_tid = $_COOKIE['tID'];

//checks if the cookie is a string of 50 characters
if (strlen($current_tid)==50){
  $TrackerID = $current_tid; //If the cookie already have a unique string, then use it!
} else {
  $TrackerID = random_gen(50); //Generates a new random string with 50 characters
}

//Set cookie "tID" with the unique variable $TrackerID
setcookie("tID",$TrackerID,time()+60*60*24*365);

因此,事实是,当用户在server1上加载website.html时,用户也在server2上加载了tracker.js,后者将带有JSON的数据发送到getdata.PHP.但是,该脚本不会发送cookie,并且每次加载脚本时getdata.PHP都会生成一个新字符串.

有什么方法可以使用JSON发送Cookie?

解决方法:

您应该使用JSONP而不是常规JSON:

在脚本中,您应该添加以下内容

$.getJSON("http://domain2.com/getdata.PHP?callback=?&"+info,
    function(data){}
);

而且,PHP脚本应该以以下格式返回JSON,而不是原始的JSON:

header("Content-Type: text/javascript");
$callback = $_GET["callback"];
print "$callback(";
// Code to produce the JSON output as normal
print ");";

More info on JSONP and jQuery is available here.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐