jquery ajax跨域
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.')'; ?>
二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.')'; ?>