简体   繁体   English

跨域请求的简单ajax POST

[英]simple ajax POST with cross domain request

I am trying to send a simple form with only one parameter to an API made by my back-end programmer, he told me that all i need to do is to send the one parameter to a given URL via POST using ajax. 我正在尝试向后端程序员制作的API发送仅包含一个参数的简单表单,他告诉我,我要做的就是使用ajax通过POST将一个参数发送到给定的URL。

The problem is I get a No 'Access-Control-Allow-Origin' header is present error. 问题是我得到一个没有'Access-Control-Allow-Origin'标头存在的错误。

I've read through this question and tried to implement the first answer's solution with no success. 我已经阅读了这个问题,并试图实现第一个答案的解决方案,但没有成功。 When i test the API via hurl it works with no problem. 当我通过hurl测试API时,没有问题。

this is the code that i am using to send the form 这是我用来发送表格的代码

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

And this is the form: 形式如下:

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

there shouldn't be any PHP involved in the process. 该过程中不应涉及任何PHP。

Any insights on what could I be doing wrong? 关于我可能做错了什么的任何见解?

Try adding crossDomain: true and xhrFields: { withCredentials: true } to the request: 尝试将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);
                }
            } 
        });                
    });
});

See http://api.jquery.com/jquery.ajax/ 参见http://api.jquery.com/jquery.ajax/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM