简体   繁体   中英

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.

The problem is I get a No 'Access-Control-Allow-Origin' header is present error.

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.

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.

Any insights on what could I be doing wrong?

Try adding crossDomain: true and xhrFields: { withCredentials: true } to the request:

$( 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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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