- web三种跨域请求数据方法
- 以下测试代码使用php,浏览器测试使用IE9,chrome,firefox,safari
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js"></script>
<script type="text/javascript" id="loadjson"></script>
<script type="text/javascript">
// 第一种
// test1.php在服务器设置请允许跨域(注意:IE9测试不通过)
$.ajax({
type: ‘POST‘,
url: ‘http://127.0.0.1:8081/test/test1.php‘,
data: ‘name=penngo‘,
dataType: ‘json‘,
success: function(msg){
$(‘#json‘).html(JSON.stringify(msg));
}
});
// 第二种
// test2.php使用jsonp
$.ajax({
type: ‘GET‘,
url: ‘http://127.0.0.1:8081/test/test2.php?callback=?‘,
data: ‘name=penngo‘,
dataType: ‘jsonp‘,
success: function(msg){
$(‘#jsonp‘).html(JSON.stringify(msg));
}
});
// 使用js标签加载方式,该方式为异步,通过testjs()回调
var testjs = function(msg){
$(‘#js‘).html(JSON.stringify(msg));
}
$(‘#loadjson‘)[0].src = ‘http://127.0.0.1:8081/test/test3.php?method=testjs&name=penngo‘;
</script>
</head>
<body>
header跨域:
<div id="json">
</div>
<br/>
jsonp跨域:
<div id="jsonp">
</div>
<br/>
js请求实现跨域:
<div id="js">
</div>
</body>
</html>
服务器端处理
test1.php
<?php
header("Access-Control-Allow-Origin: *");
$name = $_REQUEST[‘name‘];
$result = array(‘success‘=>1, ‘name‘=>$name);
echo json_encode($result);
?>
test2.php
<?php
$callback = $_REQUEST[‘callback‘];
$name = $_REQUEST[‘name‘];
$result = array(‘success‘=>1, ‘name‘=>$name);
$jsonData = json_encode($result);
echo $callback . "(" . $jsonData . ")";
?>
test3.php
<?php
$method = $_REQUEST[‘method‘];
$name = $_REQUEST[‘name‘];
$result = array(‘success‘=>1, ‘name‘=>$name);
$jsonData = json_encode($result);
echo "$method($jsonData);";
?>
IE9测试,页面输出内容
header跨域:
jsonp跨域:
{"success":1,"name":"penngo"}
js请求实现跨域:
{"success":1,"name":"penngo"}
chrome,firefox,safari测试,页面输出内容
header跨域:
{"success":1,"name":"penngo"}
jsonp跨域:
{"success":1,"name":"penngo"}
js请求实现跨域:
{"success":1,"name":"penngo"}