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

前端之家收集整理的这篇文章主要介绍了php-使JQuery中的getJSON将cookie传递到外部域? 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

文件

domain1.com/website.html

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

domain2.com/tracker.js

  1. //Get information about the user
  2. info = "(here's some things about the user)";
  3.  
  4. //Send data using JSON
  5. $.getJSON("http://domain2.com/getdata.PHP?"+info,function(data){}
  6. );

domain2.com/getdata.PHP

  1. /******
  2. * Code to save data and stuff
  3. *******/
  4.  
  5. //Get the current cookie (if any).
  6. $current_tid = $_COOKIE['tID'];
  7.  
  8. //checks if the cookie is a string of 50 characters
  9. if (strlen($current_tid)==50){
  10. $TrackerID = $current_tid; //If the cookie already have a unique string,then use it!
  11. } else {
  12. $TrackerID = random_gen(50); //Generates a new random string with 50 characters
  13. }
  14.  
  15. //Set cookie "tID" with the unique variable $TrackerID
  16. setcookie("tID",$TrackerID,time()+60*60*24*365);

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

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

最佳答案
您应该使用JSONP而不是常规JSON:

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

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

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

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

More info on JSONP and jQuery is available here.

猜你在找的jQuery相关文章