AJAX post to external url [duplicate]

白昼怎懂夜的黑 提交于 2019-12-13 09:13:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!