1.php自带头允许跨域访问
第一种方法,使用$.ajax()
jsonp.html文件
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"></meta>
<meta charset="UTF-8"></meta>
</head>
<body>
<script>
$.ajax({
url : "http://jsonp.com/jsonp.php",
type : "get",
}).done(function(data) {
console.log(data);
}).fail(function(header) {
console.log(header);
});
</script>
</body>
</html>
http://jsonp.com/jsonp.php文件
<?php
//允许跨域
header('Access-Control-Allow-Origin: *');
$json = array(
'name' => 'Tom',
'sex' => 'man'
);
echo json_encode($json);
结果输出:
{name: 'tom',sex:'man'}
第二种方法,使用$.getJSON()
jsonp.html文件
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"></meta>
<meta charset="UTF-8"></meta>
</head>
<body>
<script>
$.getJSON('http://jsonp.com/jsonp.php',function(data) {
console.log(data);
});
</script>
</body>
</html>
2.php不带头跨域访问,使用jsonp
jsonp.html文件
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"></meta>
<meta charset="UTF-8"></meta>
</head>
<body>
<script>
$.ajax({
url : "http://jsonp.com/jsonp.php",
type : "get",
dataType : "jsonp",
jsonp : 'callback',
}).done(function(data) {
console.log(data);
}).fail(function(header) {
console.log(header);
});
</script>
</body>
</html>
http://jsonp.com/jsonp.php文件
$json = array(
'name' => 'Tom',
'sex' => 'man'
);
$callback = $_GET['callback'];
echo $callback."('".json_encode($json)."')";
结果输出:
{name: 'tom',sex:'man'}
3.jsonp也可以指定返回执行某个函数
jsonp.html文件
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"></meta>
<meta charset="UTF-8"></meta>
</head>
<body>
<script>
function callbackfunc(data)
{
console.log(data);
}
$.ajax({
url : "http://jsonp.com/jsonp.php",
type : "get",
dataType : "jsonp",
jsonp : 'callback',
jsonpCallback: 'callbackfunc',
}).done(function(data) {
console.log(data);
}).fail(function(header) {
console.log(header);
});
</script>
</body>
</html>
http://jsonp.com/jsonp.php文件
$json = array(
'name' => 'Tom',
'sex' => 'man'
);
$callback = $_GET['callback'];
echo $callback."('".json_encode($json)."')";
结果输出:
{name: 'tom',sex:'man'}
{name: 'tom',sex:'man'}