1. 程式人生 > >瀏覽器跨域測試

瀏覽器跨域測試

跨域問題

一:前端瀏覽器禁用安全設置

chrome的話可以通過在命令行,輸入chrome.exe --allow-file-access-from-files --user-data-dir="C:/Chrome dev session" --disable-web-security

二:http服務器設置:

nginx的設置:

location /api {

add_header Access-Control-Allow-Origin $http_origin;

# add_header Access-Control-Allow-Origin *;

add_header Access-Control-Allow-Credentials true;

add_header Access-Control-Allow-Methods *;

add_header Access-Control-Allow-Headers $http_access_control_request_headers;

add_header Access-Control-Max-Age 3600;


proxy_set_header Host $host;

proxy_set_header X-Real-IP $remote_addr;

proxy_set_header REMOTE-HOST $remote_addr;

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

proxy_pass http://masConsole;

if ($request_method = OPTIONS){

return 200;

}

}


例子:編寫html跨域的ajax頁面:

<html>

<head>

<title>tab標簽頁</title>

<style>

* {

padding: 0;

margin: 0;

}

ul {

list-style-type: none;

}

body {

margin: 50px;

}

#ul {

height: 30px;

margin-bottom: 10px;

}

#ul li {

height: 30px;

line-height: 30px;

padding: 0 15px;

border: 1px solid #abcdef;

float: left;

margin-right: 3px;

cursor: pointer;

}

#ul li.current {

background: #abcdef;

}

#content div {

width: 300px;

height: 200px;

border: 1px solid #abcdef;

display: none;

}

#content div.show {

display: block;

}

</style>

<script src="http://libs.baidu.com/jquery/2.0.0/jquery.js"></script>

<script>

$(function () {

$("#ul li").click(function () {

/*//1.點擊li的時候切換樣式

$(this).addClass("current").siblings().removeClass("current");

//2.根據li的索引值,來確定哪個div顯示,其他div隱藏

$("#content>div").eq($(this).index()).show().siblings().hide();*/

//$(this).addClass("current").siblings().removeClass("current").parent().next().children().eq($(this).index()).show().siblings().hide();

$(this).addClass("current").siblings().removeClass("current").parent().next().find("div").eq($(this).index()).show().siblings().hide();

$.ajax({

url: 'https://mp.sda.cn:9999/api/customer/uaa/nologin/login?Session_businessId=1',

type: 'post',

data:{"nameLogin":"000044","passwordLogin":"000000"},

dataType: 'json',

success: function(data){

alert(JSON.stringify(data));

console.log(JSON.stringify(data));

},

error: function(err){

alert(JSON.stringify(err));

console.log(JSON.stringify(err));

}

});

});

});

</script>

</head>

<body>

<ul id="ul">

<li class="current">php</li>

<li>ruby</li>

<li>python</li>

</ul>

<div id="content">

<div class="show">php...介紹</div>

<div>ruby...介紹</div>

<div>python...介紹</div>

chrome的話可以通過在命令行,輸入chrome.exe --allow-file-access-from-files --user-data-dir="C:/Chrome dev session" --disable-web-security

</div>

</body>

</html>


瀏覽器跨域測試