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

后端 未结 17 2384
说谎
说谎 2020-11-21 05:06

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

相关标签:
17条回答
  • 2020-11-21 05:50

    If you want to do this in ASP.net MVC environment with JQuery AJAX, follow these steps: (this is a summary of the solution offered at this thread)

    Assume that "caller.com"(can be any website) needs to post to "server.com"(an ASP.net MVC application)

    1. On the "server.com" app's Web.config add the following section:

        <httpProtocol>
            <customHeaders>
                <add name="Access-Control-Allow-Origin" value="*" />
                <add name="Access-Control-Allow-Headers" value="Content-Type" />
                <add name="Access-Control-Allow-Methods" value="POST, GET, OPTIONS" />
            </customHeaders>
        </httpProtocol>
      
    2. On the "server.com", we'll have the following action on the controller(called "Home") to which we will be posting:

      [HttpPost]
      public JsonResult Save()
      {
          //Handle the post data...
      
          return Json(
              new
              {
                  IsSuccess = true
              });
      }
      
    3. Then from the "caller.com", post data from a form(with the html id "formId") to "server.com" as follow:

      $.ajax({
              type: "POST",
              url: "http://www.server.com/home/save",
              dataType: 'json',
              crossDomain: true,
              data: $(formId).serialize(),
              success: function (jsonResult) {
                 //do what ever with the reply
              },
              error: function (jqXHR, textStatus) {
                  //handle error
              }
          });
      
    0 讨论(0)
  • 2020-11-21 05:52

    There is one more way (using html5 feature). You can use proxy iframe hosted on that other domain, you send message using postMessage to that iframe, then that iframe can do POST request (on same domain) and postMessage back with reposnse to the parent window.

    parent on sender.com

    var win = $('iframe')[0].contentWindow
    
    function get(event) {
        if (event.origin === "http://reciver.com") {
            // event.data is response from POST
        }
    }
    
    if (window.addEventListener){
        addEventListener("message", get, false)
    } else {
        attachEvent("onmessage", get)
    }
    win.postMessage(JSON.stringify({url: "URL", data: {}}),"http://reciver.com");
    

    iframe on reciver.com

    function listener(event) {
        if (event.origin === "http://sender.com") {
            var data = JSON.parse(event.data);
            $.post(data.url, data.data, function(reponse) {
                window.parent.postMessage(reponse, "*");
            });
        }
    }
    // don't know if we can use jQuery here
    if (window.addEventListener){
        addEventListener("message", listener, false)
    } else {
        attachEvent("onmessage", listener)
    }
    
    0 讨论(0)
  • 2020-11-21 05:53

    I know this is an old question, but I wanted to share my approach. I use cURL as a proxy, very easy and consistent. Create a php page called submit.php, and add the following code:

    <?
    
    function post($url, $data) {
    $header = array("User-Agent: " . $_SERVER["HTTP_USER_AGENT"], "Content-Type: application/x-www-form-urlencoded");
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    $response = curl_exec($curl);
    curl_close($curl);
    return $response;
    }
    
    $url = "your cross domain request here";
    $data = $_SERVER["QUERY_STRING"];
    echo(post($url, $data));
    

    Then, in your js (jQuery here):

    $.ajax({
    type: 'POST',
    url: 'submit.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.');
    }
    });
    
    0 讨论(0)
  • 2020-11-21 05:55

    Should be possible with a YQL custom table + JS XHR, take a look at: http://developer.yahoo.com/yql/guide/index.html

    I use it to do some client side (js) html scraping, works fine (I have a full audio player, with search on internet/playlists/lyrics/last fm informations, all client js + YQL)

    0 讨论(0)
  • 2020-11-21 05:57
    1. Create an iFrame,
    2. put a form in it with Hidden inputs,
    3. set the form's action to the URL,
    4. Add iframe to document
    5. submit the form

    Pseudocode

     var ifr = document.createElement('iframe');
     var frm = document.createElement('form');
     frm.setAttribute("action", "yoururl");
     frm.setAttribute("method", "post");
    
     // create hidden inputs, add them
     // not shown, but similar (create, setAttribute, appendChild)
    
     ifr.appendChild(frm);
     document.body.appendChild(ifr);
     frm.submit();
    

    You probably want to style the iframe, to be hidden and absolutely positioned. Not sure cross site posting will be allowed by the browser, but if so, this is how to do it.

    0 讨论(0)
  • 2020-11-21 05:58

    If you have access to the cross domain server and don't want to make any code changes on server side, you can use a library called - 'xdomain'.

    How it works:

    Step 1: server 1: include the xdomain library and configure the cross domain as a slave:

    <script src="js/xdomain.min.js" slave="https://crossdomain_server/proxy.html"></script>
    

    Step 2: on cross domain server, create a proxy.html file and include server 1 as a master:

    proxy.html:
    <!DOCTYPE HTML>
    <script src="js/xdomain.min.js"></script>
    <script>
      xdomain.masters({
        "https://server1" : '*'
      });
    </script>
    

    Step 3:

    Now, you can make an AJAX call to the proxy.html as endpoint from server1. This is bypass the CORS request. The library internally uses iframe solution which works with Credentials and all possible methods: GET, POST etc.

    Query ajax code:

    $.ajax({
            url: 'https://crossdomain_server/proxy.html',
            type: "POST",
            data: JSON.stringify(_data),
            dataType: "json",
            contentType: "application/json; charset=utf-8"
        })
        .done(_success)
        .fail(_failed)
    
    0 讨论(0)
提交回复
热议问题