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

后端 未结 17 2388
说谎
说谎 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: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.

提交回复
热议问题