在JQuery中创建getJSON以将cookie传递给外部域?

时间:2009-09-14 12:25:51

标签: php jquery ajax json

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

文件

domain1.com/website.html

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

domain2.com/tracker.js

//Get information 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?

2 个答案:

答案 0 :(得分:2)

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

在你的脚本中你应该添加:

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

而不是原始的JSON,您的PHP脚本应该以以下格式返回您的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

答案 1 :(得分:1)

根据我的经验,允许/禁止第三方cookie是浏览器中的安全设置,默认情况下最新的Safari会被阻止(第三方cookie)。

http://www.willmaster.com/library/cookies/setting-a-cookie-on-a-remote-domain.php http://www.bobulous.org.uk/misc/third-party-cookies.html

您可以尝试: 1)从www.domain2.com include发送您的tid,并使用js在存储在www.example1.com上的cookie上设置此tid值。

2)在包含跟踪脚本时,将其更新为通过www.example1.com的cookie中存储的TID发送,作为include的参数。

这样就可以在www.domain1.com上设置cookie(因此默认情况下不会被阻止)。如果cookie值存在于www.domain1.com上,您只需要编写一个时髦的JS来将www.domain1.com TID cookie值作为参数发送到www.domain2.com上的跟踪脚本。