【问题标题】:simple ajax POST with cross domain request带有跨域请求的简单 ajax POST
【发布时间】:2015-03-29 06:11:28
【问题描述】:

我正在尝试向后端程序员制作的 API 发送一个只有一个参数的简单表单,他告诉我,我需要做的就是使用 ajax 通过 POST 将一个参数发送到给定的 URL。

问题是我得到一个 No 'Access-Control-Allow-Origin' header is present 错误。

我已阅读this 问题并尝试实施第一个答案的解决方案但没有成功。当我通过hurl 测试 API 时,它可以正常工作。

这是我用来发送表单的代码

    $( document ).ready(function() {
        $('.btnEnviar').click(function(){
            $.ajax({
                type: 'POST',
                url: 'http://xxxxx.xxx/subscribers/subscribeEmail',
                datatype: 'jsonp',
                async: true,
                success:function(){
                    try{
                        alert("ok");
                    }catch (e){
                        alert(e);
                    }
                } 
            });                
        });
    });

这是形式:

<form class="newsletter" method="post" action="http://xxxxx.xxx/subscribers/subscribeEmail">
                    <input type="text" placeholder="mail here!" class="input" name="email">
                    <input type="submit" class="send pull-right hidden" value="Subscribe me!" placeholder="Subscribe me!">
                    <span class="btnEnviar"><i class="fa fa-envelope"></i></span>
                </form>

在这个过程中不应该有任何 PHP 参与。

关于我可能做错了什么的任何见解?

【问题讨论】:

  • 如果我发送没有 ajax 的表单,我会从 API 得到正确的响应,所以这只是我的 ajax 脚本的问题

标签: jquery ajax post cross-domain


【解决方案1】:

尝试在请求中添加crossDomain: truexhrFields: { withCredentials: true }

$( document ).ready(function() {
    $('.btnEnviar').click(function(){
        $.ajax({
            type: 'POST',
            url: 'http://xxxxx.xxx/subscribers/subscribeEmail',
            datatype: 'jsonp',
            async: true,
            xhrFields: {
               withCredentials: true
            },
            crossDomain: true,
            success:function(){
                try{
                    alert("ok");
                }catch (e){
                    alert(e);
                }
            } 
        });                
    });
});

http://api.jquery.com/jquery.ajax/

【讨论】:

  • 试过了,得到一个 net::ERR_NAME_RESOLUTION_FAILED 错误
  • @user2770956 可能是因为xxxxx.xxx 不是真正的网址,但这是您在问题中给出的网址。
  • 真是个白痴。我修复了它,但现在我得到了与以前相同的错误没有“访问控制允许来源”存在。
  • 服务器端需要在响应中设置“Access-Control-Allow-Origin”标头。告诉你的后端程序员添加它。
  • 但是如果我尝试使用 hurl.it 的 API(它也是另一个域)它可以正常工作
猜你喜欢
  • 2012-04-15
  • 2015-01-28
  • 1970-01-01
  • 1970-01-01
  • 2012-05-10
  • 2013-11-09
  • 1970-01-01
  • 2023-03-30
  • 2013-03-06
相关资源
最近更新 更多