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

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

    If you have access to all servers involved, put the following in the header of the reply for the page being requested in the other domain:

    PHP:

    header('Access-Control-Allow-Origin: *');
    

    For example, in Drupal's xmlrpc.php code you would do this:

    function xmlrpc_server_output($xml) {
        $xml = ''."\n". $xml;
        header('Connection: close');
        header('Content-Length: '. strlen($xml));
        header('Access-Control-Allow-Origin: *');
        header('Content-Type: application/x-www-form-urlencoded');
        header('Date: '. date('r'));
        // $xml = str_replace("\n", " ", $xml); 
    
        echo $xml;
        exit;
    }
    

    This probably creates a security problem, and you should make sure that you take the appropriate measures to verify the request.

提交回复
热议问题