跨域案例下载:https://sdeno.com/?p=4815
JSONP是一个非官方的协议,它允许在服务器端集成Script tags返回至客户端,通过javascript callback的形式实现跨域访问
方法一: jsonp之 getJSON
js
var url = "http://localhost/mytest/jsonp_php.php?callback=?";
$.getJSON(url, {
"age": 21,
"name": "kitty"
}, function (data) {
alert("name:" + data.name + ", age:" + data.age);
});
php
<?php
$age=$_GET["age"];
$name=$_GET["name"];
$jsondata = "{age:$age, name:'$name'}";
echo $_GET['callback'].'('.$jsondata.')';
?>
关于jquery $.getJSON()跨域请求一些细节:https://sdeno.com/?p=3247
二jsonp之$.ajax
js
$.ajax({
type: 'GET',
url: 'http://localhost/mytest/jsonp_php.php',
dataType: "jsonp",
jsonp: "callback5",
jsonpCallback:"flightHandler",
data: {
"age": 21,
"name": "kitty"
},
success: function (data) {
alert("name:" + data.sd + ", age:" + data.aa)
}
})
php
<?php
$age=$_GET["age"];
$name=$_GET["name"];
$ary=array("sd"=>"sdfg","aa"=>23);
$jsondata=json_encode($ary);
echo $_GET['callback5'].'('.$jsondata.')';
?>
http://www.cnblogs.com/breakdown/archive/2012/04/27/2473586.html