为什么我从域中的iframe创建会话然后尝试从另一个iframe访问会话时工作正常但是当我尝试通过ajax访问会话时它不起作用?
<?php
header("Access-Control-Allow-Origin: *");
session_start();
if(isset($_POST['session'])){
$_SESSION['session'] = $_POST['session'];
echo "created session";
}else if(isset($_GET['want'])){
//for ajax request
die($_SESSION['session']);
}
?>
<form action="iframe.php" method="post">
SESSION VAL:<input name="session" value="<?php echo $_SESSION['session']?>" type="text"/><br>
<input type="submit"/>
</form>
<iframe src="iframe.php">
</iframe>
<br>SESSION FROM AJAX:
<div id="AJAX"></div>
window.setInterval(function(){
$.get( "iframe.php?want", function( data ) {
$( "#AJAX" ).html( data );
});
},1000);
答案 0 :(得分:2)
了解如何做CORS。不久,要使浏览器使用ajax发送会话,您必须在xhr中添加一些字段:
$.ajax({
url : "https://crypter.co.uk/iframe.php?want",
xhrFields : {
withCredentials : true // <-- this
},
success : function( data ) {
$( "#AJAX" ).html( data );
}
});
您必须允许此类服务请求,请参阅this answer。