AJAX发布到外部网址 [英] AJAX post to external url

查看:97
本文介绍了AJAX发布到外部网址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下代码将ajax的数据发布到外部网址:

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();
    });
});

但是我遇到以下错误:

XMLHttpRequest无法加载 http://site.com/post.php . Access-Control-Allow-Origin不允许使用Origin null.

XMLHttpRequest cannot load http://site.com/post.php. Origin null is not allowed by Access-Control-Allow-Origin.

我还在服务器上的htaccess文件中添加了以下行

I have also added the the following line to the htaccess file on my server

Header set Access-Control-Allow-Origin *

谁能告诉我我做错了什么以及如何将数据发布到外部URL?

Would anyone be able to tell me what I am doing wrong and how I can post data to an external url?

推荐答案

外部网址是您的吗?如果没有,那是不可能的.如果是,则必须在该域上返回以下标头:

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

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

More info can be found here: https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS

如果不是您的域,则必须创建代理,然后创建一个PHP文件,该文件从该域中获取所需的内容.然后将ajax请求发送到您自己的域.

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.

这篇关于AJAX发布到外部网址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆