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

后端 未结 17 2399
说谎
说谎 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 06:01

    If you control the remote server, you should probably use CORS, as described in this answer; it's supported in IE8 and up, and all recent versions of FF, GC, and Safari. (But in IE8 and 9, CORS won't allow you to send cookies in the request.)

    So, if you don't control the remote server, or if you have to support IE7, or if you need cookies and you have to support IE8/9, you'll probably want to use an iframe technique.

    1. Create an iframe with a unique name. (iframes use a global namespace for the entire browser, so pick a name that no other website will use.)
    2. Construct a form with hidden inputs, targeting the iframe.
    3. Submit the form.

    Here's sample code; I tested it on IE6, IE7, IE8, IE9, FF4, GC11, S5.

    function crossDomainPost() {
      // Add the iframe with a unique name
      var iframe = document.createElement("iframe");
      var uniqueString = "CHANGE_THIS_TO_SOME_UNIQUE_STRING";
      document.body.appendChild(iframe);
      iframe.style.display = "none";
      iframe.contentWindow.name = uniqueString;
    
      // construct a form with hidden inputs, targeting the iframe
      var form = document.createElement("form");
      form.target = uniqueString;
      form.action = "http://INSERT_YOUR_URL_HERE";
      form.method = "POST";
    
      // repeat for each parameter
      var input = document.createElement("input");
      input.type = "hidden";
      input.name = "INSERT_YOUR_PARAMETER_NAME_HERE";
      input.value = "INSERT_YOUR_PARAMETER_VALUE_HERE";
      form.appendChild(input);
    
      document.body.appendChild(form);
      form.submit();
    }
    

    Beware! You won't be able to directly read the response of the POST, since the iframe exists on a separate domain. Frames aren't allowed to communicate with each other from different domains; this is the same-origin policy.

    If you control the remote server but you can't use CORS (e.g. because you're on IE8/IE9 and you need to use cookies), there are ways to work around the same-origin policy, for example by using window.postMessage and/or one of a number of libraries allowing you to send cross-domain cross-frame messages in older browsers:

    • Porthole
    • XSSInterface
    • EasyXDM
    • jQuery PostMessage Plugin

    If you don't control the remote server, then you can't read the response of the POST, period. It would cause security problems otherwise.

提交回复
热议问题