跨域請求問題

跨域請求,需要提供安全並且服務器認可的信息。

比如:A域名下的數據需要請求B域名下的一個方法,需要進行驗證,或者可能需要獲取B域名下cookie的某一個值,那麼需要進行跨域請求。

如果我們使用普通的Ajax的json格式來進行請求,則會出現


XMLHttpRequest cannot load http://zhl.study.com/cross-domain.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.


的錯誤,那麼需要在服務器上加上:(背景是***的代碼)

server
     {
        listen       80;
        server_name zhl.study.com;
        index  index.html index.php;
        root  /var/www/study;
        error_log  logs/study_error.log  debug;
        access_log  /var/log/nginx/www_access.log  wwwlogs;

        location / {
                       try_files $uri $uri/ /index.php?$args;
                   }

        location ~ .*\.(php|php5)?$
        {

          add_header 'Access-Control-Allow-Origin' 'http://localhost';
          add_header 'Access-Control-Allow-Credentials' 'true';


          fastcgi_pass  127.0.0.1:9000;
          fastcgi_index index.php;
          #fastcgi_intercept_errors on;
          include fcgi.conf;
          #log_by_lua_file conf/lua/stats/record.lua;
        }
    }

如果使用JSONP的方式則不需要添加上述***的代碼區域


$.ajax({  
                url: 'http://zhl.study.com/diff_domain.php',
                type: "GET",
                dataType: 'jsonp',
                jsonp:'callback',
                timeout: 5000,  
                success: function (data) {
                    alert(data.name);        
                    
                },
                error: function(data){

                }
            })


在B域名下設置cookie,返回之中帶有cookie的數據,即可。

參考文檔:

    http://api.jquery.com/jQuery.ajax/

http://www.w3cschool.cn/ajax_ajax.html


如果在A下設置cookies,需要到B域名下獲取cookie,然後進行驗證,此方法目前未能繼續實現(A與B域名毫無關係,如果是一級和二級域名關係的除外),如果你已經實現此方法可以給我聯繫。Email:[email protected]

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章