发送跨域请求记录数据
我在一个广告平台工作。当有人单击图像时,我想将请求发送回我的服务器以记录此操作。我有一个预先生成的网址。如果我向此网址发送请求,它将记录数据。
我的问题是日志 url 在我的域中,而 javascript 是在客户端的域中执行的。在不修改日志记录 php 脚本(添加诸如 Access-Control-Allow-Origin: * 之类的内容)的情况下,有没有办法将此请求发送到新域?
由于我只记录数据,因此服务器仅发回文本“OK”(这是我不需要的信息)。
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. 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?
Since I'm only logging data, the server only sends back the text "OK" (which is information I don't need).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您应该能够向任何域发送 Ajax HTTP 请求。我不明白问题是什么......这是受同源策略限制的响应,而不是请求本身。如果域不匹配,您将无法访问 PHP 脚本的响应,但服务器将正常处理请求,即使该请求来自不同的域。
You should be able to send Ajax HTTP requests to any domain. 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.
这是一个 hack,但很常用。单击时将图像附加到 DOM,并将 src 设置为日志记录 URL。为了方便起见,让日志记录 URL 的输出为 1x1 像素图像。您必须通过 GET 字符串传递参数,但它会起作用。
This is a hack but it's commonly used. On click append an image to the DOM with the src set to the logging URL. To be friendly, have the output from the logging URL be a 1x1 pixel image. You'll have to pass the parameters via a GET string but it will work.
使用您的域(图像或 iframe)上的源创建任何动态 DOM 元素,将日志记录数据附加到请求。
您的日志请求现在将显示在 IIS 日志中
Create any dynamic DOM element with source on your domain (image or iframe), append a logging data to a request.
Your log requests will now appear in IIS logs
作为安全预防措施,跨域脚本限制是在浏览器级别强制执行的,因此没有简单的代码修复可以解决这些问题。但是,您可以将
JSONP
(带有填充的 JSON)作为起点。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.您可以创建一个隐藏的
iframe
,并将src
属性设置为日志记录 URL。这至少和上面列出的图像方法一样丑陋。You could create a hidden
iframe
with thesrc
attribute set to the logging URL. This is at least as ugly as the image approach listed above.