jquery ajax跨越
JSONP是一个非官方的协议,它允许在服务器端集成Script tags返回至客户端,通过javascript callback的形式实现跨域访问
1、jsonp之$.ajax
js
$.ajax({ type: 'GET', url: 'http://localhost/ajax/jsonp.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"=>"tom","aa"=>23); $jsondata=json_encode($ary); echo $_GET['callback5'].'('.$jsondata.')'; ?>
2、jsonp之 getJSON
js
var url = "http://localhost/ajax/jsonp.php?callback=?"; $.getJSON(url, { "age": 21, "name": "kitty" }, function (data) { alert("name:" + data.name + ", age:" + data.age); });
php
$age=$_GET["age"]; $name=$_GET["name"]; $jsondata = "{age:$age, name:'$name'}"; echo $_GET['callback'].'('.$jsondata.')';