Ajax - How do I send a cross-domain POST request via JavaScript

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

How do I send a cross-domain POST request via JavaScript?

Notes - it shouldn t refresh the page, and I need to grab and parse the response afterward.

Your help with some code examples will be much appreciated.

Answers

http://www.html5rocks.com/en/tutorials/cors/ http://www.html5rocks.com/en/tutorials/cors/

If you control the server being POSTed, simply leverage the "Cross-Origin Resource Sharing standard" by setting response headers on the server. This answer is discussed in other answers in this thread, but not very clearly in my opinion.

In short here is how you accomplish the cross domain POST from from.com/1.html to to.com/postHere.php (using PHP as an example). Note: you only need to set Access-Control-Allow-Origin for NON OPTIONS requests - this example always sets all headers for a smaller code snippet.

    • In postHere.php setup the following:
    switch ($_SERVER[ HTTP_ORIGIN ]) {
        case  http://from.com : case  https://from.com :
        header( Access-Control-Allow-Origin:  .$_SERVER[ HTTP_ORIGIN ]);
        header( Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS );
        header( Access-Control-Max-Age: 1000 );
        header( Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With );
        break;
    }
    
    This allows your script to make cross domain POST, GET and OPTIONS. This will become clear as you continue to read...
    • Setup your cross domain POST from JS (jQuery example):
    $.ajax({
        type:  POST ,
        url:  https://to.com/postHere.php ,
        crossDomain: true,
        data:  {"some":"json"} ,
        dataType:  json ,
        success: function(responseData, textStatus, jqXHR) {
            var value = responseData.someKey;
        },
        error: function (responseData, textStatus, errorThrown) {
            alert( POST failed. );
        }
    });
    

https://from.com https://from.com

https://developer.mozilla.org/en/http_access_control https://developer.mozilla.org/en/http_access_control

Keep in mind the following if you do this:

    • Your server will have to handle 2 requests per operation
    • You will have to think about the security implications. Be careful before doing something like Access-Control-Allow-Origin: *
    • This wont work on mobile browsers. In my experience they do not allow cross domain POST at all. I ve tested android, iPad, iPhone
    http://bugs.jquery.com/ticket/7868#comment:11 http://bugs.jquery.com/ticket/7868#comment:11
    • Always return the headers above, not just on OPTION requests. FF needs it in the response from the POST.

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/298745/how-do-i-send-a-cross-domain-post-request-via-javascript

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils