简体   繁体   中英

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

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.

Create any dynamic DOM element with source on your domain (image or iframe), append a logging data to a request.

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

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.

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.

You could create a hidden iframe with the src attribute set to the logging URL. This is at least as ugly as the image approach listed above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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