如何使ajax跨域的几种简单方法
方法一:利用iframe远程获取JavaScript数据
页面1:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk" />
<title>iframe跨域取值</title>
<script type="text/javascript">
function test()
{
document.getElementById("getscript").innerHTML = '<iframe src="roulette.php" frameborder="0" width="0" height="0"></iframe>';
}
function showmsg()
{
alert("通过iframe调用showmsg()方法成功!");
}
</script>
</head>
<body>
<div id="getscript" style="display:none"></div>
<input type="button" value="测试" onclick="test();" />
</body>
</html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk" />
<title>iframe跨域取值</title>
<script type="text/javascript">
function test()
{
document.getElementById("getscript").innerHTML = '<iframe src="roulette.php" frameborder="0" width="0" height="0"></iframe>';
}
function showmsg()
{
alert("通过iframe调用showmsg()方法成功!");
}
</script>
</head>
<body>
<div id="getscript" style="display:none"></div>
<input type="button" value="测试" onclick="test();" />
</body>
</html>
页面2:
<?php
header("content-type:text/html; charset=gbk");
echo '<script>parent.showmsg()</script>';
?>
header("content-type:text/html; charset=gbk");
echo '<script>parent.showmsg()</script>';
?>
方法二:巧用script远程获取JavaScript数据
页面1:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk" />
<title>巧用script远程获取数据</title>
<script id="getscript" type="text/javascript" src=""></script>
<script type="text/javascript">
function test()
{
var obj = document.getElementById("getscript");
obj.src = "roulette.php";
}
function showmsg()
{
alert("通过script调用showmsg()方法成功!");
}
</script>
</head>
<body>
<input type="button" value="测试" onclick="test();" />
</body>
</html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk" />
<title>巧用script远程获取数据</title>
<script id="getscript" type="text/javascript" src=""></script>
<script type="text/javascript">
function test()
{
var obj = document.getElementById("getscript");
obj.src = "roulette.php";
}
function showmsg()
{
alert("通过script调用showmsg()方法成功!");
}
</script>
</head>
<body>
<input type="button" value="测试" onclick="test();" />
</body>
</html>
页面2:
<?php
header("content-type:text/html; charset=gbk");
echo 'showmsg();';
?>
header("content-type:text/html; charset=gbk");
echo 'showmsg();';
?>