-2

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?

4

2 回答 2

3

外部 URL 是您的吗?如果不是,那是不可能的。如果是,您必须在该域上返回以下标头:

Access-Control-Allow-Origin: http://your.domain.com

或者,如果您想允许所有域:

Access-Control-Allow-Origin: *

更多信息可以在这里找到:https ://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS

如果不是您的域,您必须创建一个代理,创建一个 PHP 文件,从该域获取您需要的内容。并对您自己的域执行 ajax 请求。

于 2013-05-09T15:12:07.157 回答
0

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: *

于 2013-05-09T15:12:58.120 回答