简体   繁体   English

发送跨域请求以记录数据

[英]Send a cross-domain request to log data

I'm working on an ad platform. 我正在一个广告平台上工作。 When someone clicks on an image, I want to send a request back to my server to log this action. 当有人单击图像时,我想将请求发送回我的服务器以记录此操作。 I have a pre-generated url for this. 我有一个预先生成的网址。 If I send a request to this url, it will log the data. 如果我向该网址发送请求,它将记录数据。

My issue is that the log url is on my domain, whereas the javascript is being executed in a client's domain. 我的问题是日志网址位于我的域中,而javascript正在客户端的域中执行。 Without modifying the logging php script (to add something like Access-Control-Allow-Origin: *), is there a way to send this request to the new domain? 无需修改日志php脚本(添加类似Access-Control-Allow-Origin:*的内容),是否可以将请求发送到新域?

Since I'm only logging data, the server only sends back the text "OK" (which is information I don't need). 由于我仅记录数据,因此服务器仅发送回文本“ OK”(这是我不需要的信息)。

This is a hack but it's commonly used. 这是一个hack,但是很常用。 On click append an image to the DOM with the src set to the logging URL. 单击后,将图像添加到DOM,并且将src设置为日志记录URL。 To be friendly, have the output from the logging URL be a 1x1 pixel image. 为方便起见,请使记录URL的输出为1x1像素的图像。 You'll have to pass the parameters via a GET string but it will work. 您必须通过GET字符串传递参数,但是它将起作用。

Create any dynamic DOM element with source on your domain (image or iframe), append a logging data to a request. 使用您的域(图像或iframe)上的源创建任何动态DOM元素,并将日志记录数据附加到请求中。

var logData = function(data){
if(data === undefined){
    return;
}

var img=document.createElement("img");
img.setAttribute('src', 'http://another.domain?'+data);
img.setAttribute('height', '1px');
img.setAttribute('width', '1px');
document.body.appendChild(img);}

Your log requests will now appear in IIS logs 您的日志请求现在将出现在IIS日志中

You should be able to send Ajax HTTP requests to any domain. 您应该能够将Ajax HTTP请求发送到任何域。 I don't see what the problem is... It's the response that is restricted with the Same Origin Policy, not the request itself. 我看不出问题出在哪里……这是受“相同来源策略”限制的响应,而不是请求本身。 You cannot access the response of the PHP script if the domains don't match, but the server will process the request normally, even if it's from a different domain. 如果域不匹配,则无法访问PHP脚本的响应,但是服务器将正常处理请求,即使请求来自其他域也是如此。

Cross-domain script restrictions are enforced at the browser level as a security precaution, so there is not a simple code fix to work around them. 为了安全起见,在浏览器级别强制执行跨域脚本限制,因此没有简单的代码修补程序可以解决这些问题。 However, you can look at JSONP (JSON with padding) as a starting point. 但是,您可以将JSONP (带填充的JSON)作为起点。

You could create a hidden iframe with the src attribute set to the logging URL. 您可以使用src属性设置为日志记录网址来创建隐藏的iframe This is at least as ugly as the image approach listed above. 这至少与上面列出的图像方法一样难看。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM