问题
I am trying to post data with ajax to an external url with the following code:
$(document).ready(function(){
$('.submit_button').click(function() {
$.ajax({
type : 'POST',
url : 'http://site.com/post.php',
dataType : 'text',
data: $("#infoForm").serialize()
}).done(function(results) {
alert(results);
});
event.preventDefault();
});
});
But I am getting the following error:
XMLHttpRequest cannot load http://site.com/post.php. Origin null is not allowed by Access-Control-Allow-Origin.
I have also added the the following line to the htaccess file on my server
Header set Access-Control-Allow-Origin *
Would anyone be able to tell me what I am doing wrong and how I can post data to an external url?
回答1:
Is the external URL yours? If no, it's not possible. If yes you have to return the following headers on that domain:
Access-Control-Allow-Origin: http://your.domain.com
Or if you want to allow all domains:
Access-Control-Allow-Origin: *
More info can be found here: https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS
If it's not your domain you have to create a proxy, create a PHP file that gets the content you need from that domain. And do your ajax request to your own domain.
回答2:
You cannot use Ajax to send requests to another domain, unless you make use of CORS. This is due to the same-origin policy. If you own the server, you can set up CORS in Apache by making an .htaccess
file with the contents Access-Control-Allow-Origin: *
来源:https://stackoverflow.com/questions/16465085/ajax-post-to-external-url