制作的getJSON在JQuery中通过cookie来外部域? [英] Make getJSON in JQuery to pass cookies to external domain?

查看:254
本文介绍了制作的getJSON在JQuery中通过cookie来外部域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用的getJSON在JQuery的外部域即发不包括饼干该域的请求。我用这个对于我写我的分析剧本,我需要在那里的脚本运行,所以我可以跟踪唯一访问者外部域设置cookie。

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.

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

那么,事情是,当用户负载website.html在Server1上,用户还加载tracker.js Server2上,它发送一些数据使用JSON来getdata.php。不过,此脚本不会发送cookie和getdata.php将每一个脚本加载时间产生一个新的字符串。

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.

有什么办法来发送使用JSON饼干?

Is there any way to send cookies using JSON?

推荐答案

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

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

代替了原来的JSON,你的PHP脚本应该返回您JSON格式:

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

对JSONP和jQuery

更多信息,请点击这里

More info on JSONP and jQuery is available here.

这篇关于制作的getJSON在JQuery中通过cookie来外部域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆