基于安全原因,默认 ajax (XMLHTTPRequest ) 是不能跨域的。
有很多解决方案,我就不赘述了,见下面的链接:
http://bob.pythonmac.org/archives/2005/12/05/remote-json-jsonp/
我想说的是jquery jsonp的操作和 原理( 原理我也是转载别人的)
原理
客户端:
<script type="text/javascript">
function test(data) {
alert(data);
}
</script>
<script type="text/javascript" src="http://******.php?callback=test"></script>
服务端:
$fun = $_GET["callback"];
echo $fun. "(‘你好世界’)";
jquery jsonp php实例
服务器上的jsonp.php
<?php
$callback = isset($_GET["callback"])?$_GET["callback"]:"callback";
$foo = isset($_GET["foo"])?$_GET["foo"]:"’";
$format = isset($_GET["format"])?$_GET["format"]:"";
$array = array("foo"=>$foo,"format"=>$format);
echo $callback . "(". json_encode($array). ")";
?>
本地html:
<!DOCTYPE html>
<html>
<head>
<style>img{ height: 100px; float: left; }</style>
<script src="http://code.jquery.com/jquery-1.5.js"></script>
</head>
<body>
<div id="images">
</div>
<script>
$.getJSON("http://your.server.com/jsonp.php?callback=?",
{
foo: "bar",
format: "json"
},
function(data) {
alert(data.format);
});</script>
</body>
</html>
官方文档:http://api.jquery.com/jQuery.getJSON/
jquery 1.5 的G点在于:关键点在于请求的url 包含:?callback=?