Php 在JQuery中生成getJSON以将Cookie传递到外部域?

Php 在JQuery中生成getJSON以将Cookie传递到外部域?,php,jquery,ajax,json,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 = "(her

当我在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){} ); //获取有关用户的信息 info=“(这里有一些关于用户的信息)”; //使用JSON发送数据 $.getJSON(“http://domain2.com/getdata.php?“+信息, 函数(数据){} ); 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); /****** *保存数据和内容的代码 *******/ //获取当前cookie(如果有)。 $current_tid=$\u COOKIE['tid']; //检查cookie是否为50个字符的字符串 如果(strlen($current_tid)==50){ $TrackerID=$current\u tid;//如果cookie已经有一个唯一的字符串,那么就使用它! }否则{ $TrackerID=random_gen(50);//生成一个包含50个字符的新随机字符串 } //使用唯一变量$TrackerID设置cookie“tID” setcookie(“tID”,$TrackerID,time()+60*60*24*365); 所以,问题是,当用户在server1上加载website.html时,用户也在server2上加载tracker.js,后者将一些带有JSON的数据发送到getdata.php。但是,脚本不会发送cookies,每次加载脚本时,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 ");";

.

根据我的经验,允许/禁止第三方Cookie是浏览器中的一种安全设置,最新的safari默认会阻止它(第三方Cookie)

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

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


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

通过打印整个cookie数组(print\r)来检查问题是否确实是cookie,或者是其他问题。。。我有点喜欢你的想法,我刚刚想出了一个非常好的编码方法!谢谢我认为这可能是跨域存储Cookie数据的最可靠的方法,并且不会被默认的浏览器设置(阻止第三方Cookie)阻止,而原始jsonp可能会遭受这种情况。如果有人知道存储第三方数据的更可靠的方法,请告知。