Make getJSON in JQuery to pass cookies to external domain?

匿名 (未验证) 提交于 2019-12-03 08:54:24

问题:

When I use getJSON in JQuery to an external domain the request that is made does not include cookies for that domain. I'm using this for my analytics script that I am writing and I need to set a cookie on the external domain where the script is running so I can track unique visitors.

The files

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);

So, the thing is that when the user loads website.html on server1, the user also loads tracker.js on server2 which sends some data with JSON to getdata.php. However, the script does not send cookies and getdata.php will generate a new string every time the script is loaded.

Is there any way to send cookies using JSON?

回答1:

You should use JSONP instead of regular JSON:

In you script you should add this:

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

And instead of the original JSON, you PHP script should return your JSON in the format:

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.



回答2:

In my experience, allowing / disallowing 3rd party cookies is a security setting in the browser, which the latest safari blocks by default (3rd party cookies).

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

You could try: 1) Send your tid from www.domain2.com include, and use the js to set this tid value on a cookie stored on www.example1.com.

2) When including your tracking script, update it to send across the TID stored in www.example1.com's cookie, as a parameter for the include.

This way the cookie is set on www.domain1.com (so wont get blocked be default). You just need to write a funky bit of JS to send the www.domain1.com TID cookie value as a parameter to the tracking script on www.domain2.com, if the cookie value exists on www.domain1.com.



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!