jsonp跨域请求的几种方式

来源:互联网 发布:足球数据库 编辑:程序博客网 时间:2024/04/30 12:58
demo.html<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8"><title>Document</title><script src="jquery.js"></script></head><body><button>查看</button><script>//方法一$('button').click(function(){var url="http://www.json.com/day19/demo.php?callback=?";$.get(url,function(msg){for(i in msg){alert(msg[i].d_desc)}},'jsonp')})//方法二 $('button').click(function(){var url="http://www.json.com/day19/demo.php";$.get(url,function(msg){alert(msg)})})//方法三$('button').click(function(){var url="http://www.json.com/day19/demo.php";$.getScript(url,function(msg){for(v in data){//alert(data[v])alert(data[v].d_desc)}},'jsonp')})</script></body></html>

demo.php

<?phpheader('Access-Control-Allow-Origin:*');$pdo=new PDO('mysql:host=127.0.0.1;dbname=php7','root','root');$pdo->exec('set names utf8');$sql="select * from day11";$data=$pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);$str=json_encode($data);$callback=$_GET['callback'];echo $callback."(".$str.")";//echo "var data={$str}";?>

注:
header('Access-Control-Allow-Origin:*');
CORS  跨域资源共享  以上的配置的含义是允许任何域发起的请求都可以获取当前服务器的数据。当然,这样有很大的危险性,恶意站点可能通过XSS攻击我们的服务器。所以我们应该尽量有针对性的对限制安全的来源,例如下面的设置使得只有http://blog.csdn.net这个域才能跨域访问服务器的API。

<span><span>Access-Control-Allow-Origin: http://blog.csdn.net  </span></span> 
 以前要实现跨域访问,可以通过JSONP、Flash或者服务器中转的方式来实现,但是现在我们有了CORS。

        CORS与JSONP相比,无疑更为先进、方便和可靠。

        1、 JSONP只能实现GET请求,而CORS支持所有类型的HTTP请求。

        2、 使用CORS,开发者可以使用普通的XMLHttpRequest发起请求和获得数据,比起JSONP有更好的错误处理。

        3、 JSONP主要被老的浏览器支持,它们往往不支持CORS,而绝大多数现代浏览器都已经支持了CORS(这部分会在后文浏览器支持部分介绍)。



0 0