English 中文(简体)
Can I use XMLHttpRequest on a different port from a script file loaded from that port?
原标题:

I have website that use XMLHttpRequest (jQuery, actually). I also have another site running on the same server, which serves a script file that makes XHR requests back to THAT site, ie.

http://mysite:50000/index.html includes

<script src="http://mysite:9000/otherscript.js"></script>

and http://mysite:9000/otherscript.js includes

$.ajax({
    url:  http://mysite:9000/ajax/stuff 
});

The problem is - this doesn t work. The AJAX requests from the loaded script simply fail with no error message. From what I ve been able to find this is the old same origin policy. Given that I control both sites, is there anything I can do to make this work? The "document.domain" trick doesn t seem to do a thing for XMLHttpRequest.

最佳回答

Nope- can t do this with XHR. Same-domain policy is very restrictive there- same host, same port, same protocol. Sorry! You ll have to resort to other tricks (iframes, title manipulation, etc) to get it to work.

问题回答

You can do this by adding Access-Control-Allow-Origin header.

If you are using PHP

header("Access-Control-Allow-Origin: http://example.com");

or in Node.js

response.writeHead(200, { Access-Control-Allow-Origin :  http://example.com });

This should do the trick for you. It always works for me.

I just solved a similar issue with a PHP service I m currently playing around with (not sure how relevant a PHP solution is to this directly, but...) by making a single line proxy PHP page, SimpleProxy.php:

<?php
echo file_get_contents( http://localhost:4567 );
?>

And in my XMLHttpRequest I use SimpleProxy.php in place of http://localhost:4567 , which effectively puts the request on the same domain as my .js code.





相关问题
ajax login using httpRequest?

I am trying to develop my login script to give feedback to the user if the login is valid or not. Basically if it isn t correct a div box will show saying its wrong, if its correct it will show its ...

Virtual Tour using sketch up, ajax, flash technologies

I want to know if there are existing technology that make your 3d models in sketch into virtual tours, using either Ajax or Flash for web presentation. If there s none, which will be a good approach ...

How can i update div continuously

I have asp.net application where i have a div which showing the value from other site. The value of that site is changing continuously. I want that my div will automatically update in some interval ...

热门标签