Xhr the front cross-domain reasons and three solutions

Front-end cross-domain solutions 
· cross-domain browser made for security restriction policy 
-browser requests must follow the same origin policy: the same domain name, with the port, with the agreement of 


1 : Cross-domain Cros 
    This method is resolved in the service side 
    php settlement cases: 
        // mode 1: 
        header ( " Access-Control-the allow-Origin: * " ); // allow all addresses cross-domain requests
         // Second way: 
        header ( " Access-Control-the allow-Origin: HTTP: localhost //: 8080 " ); // specify an address can be cross-domain requests, there can only specify one 

        // three ways: If you want to allow cross-domain requests multiple addresses can be written 
        $ Origin = [ ' HTTP: // localhost: 8080 ' , ' HTTP: // localhost: 8081 ' ];
        $ AllowOrigin = ' HTTP: // localhost: 8080 ' ;
         IF (the in_array ($ _ SERVER [ " HTTP_ORIGIN " ], $ Origin)) 
        { 
            $ AllowOrigin = $ _SERVER [ " HTTP_ORIGIN " ]; 
        } 
        header ( " Access-Control-the Allow -Origin: " $ AllowOrigin);.
 2 : JSONP 
    this method requires front-end back-end are set 
    ajax request by the same-origin policy influence, does not allow cross-domain requests, and links script tag src attribute, but can be accessed across domains the js script, 
    take advantage of this feature, the server no longer returns data in JSON format, but return some js code to call a function, so to achieve cross-domain. 
    DETAILED distal realization:
         <Script the src = "http://www.fengxiangqu.com/file/wd-js/jquery-1.11.1.min.js " > </ Script> 
        <Script> 
            $ .ajax ({ 
            type: " GET " , 
            URL: " HTTPS: //order.imooc.com/pay/cartorder " , 
            dataType: " jsonp " , 
            jsonp: " callback " , // passed to the request handler or page to get jsonp callback function name parameter name (default: callback) 
            jsonpCallback: " jsonpcallback " , // since jsonp defined callback function name, the default name for the random function automatically generated jQuery
            Success: function (JSON) { 
            the console.log (JSON); 
            }, 
            error: function () { 
                
            } 
        });
         </ Script> 
    backend implementation:
         <? PHP 
            $ Data = " ....... " ; 
            callback $ = ' jsonpcallback ' ; 
            echo $ callback. ' ( ' .json_encode (the Data $). ' ) ' ; 
            Exit;
         >?
 3 : nginx proxy forwards

 

Guess you like

Origin www.cnblogs.com/cl94/p/12443843.html