ajax跨域請求(攜帶cookie)springboot
阿新 • • 發佈:2018-12-10
ajax跨域請求(攜帶cookie)
一般而言,對於跨域 XMLHttpRequest 或 Fetch 請求,瀏覽器不會發送身份憑證資訊。如果要傳送憑證資訊,需要設定 XMLHttpRequest 的某個特殊標誌位。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>跨域測試</title>
<script type="text/javascript" src="js/jquery-1.11.3.min.js"></script >
<script type="text/javascript">
function myAjax(){
$.ajax({
url: 'http://localhost:8081/cors/getTime',
type: 'post',
dataType:'json',
//async:false,
data: {
"name" : "孫悟空"
},
xhrFields:{withCredentials: true },
success:function(result){
//顯示在 font 標籤
$("#show").html(result);
}
});
}
</script>
</head>
<body>
<input type="button" value="以ajax(post)方式獲取當前時間" onclick="myAjax()" />
<br/>
當前時間:
<font id="show"></font>
</body>
</html>
其中:
@RestController
@RequestMapping("/cors")
public class GetTime {
@RequestMapping("/getTime")
@CrossOrigin(origins="http://localhost:8080",allowCredentials="true")
public Date getTime(String name) {
System.out.println(name);
return new Date();
}
}
攜帶cookie:
未攜帶cookie:
其他ajax方式:
$.ajax({
...
xhrFields: {
withCredentials: true
}
});