同一个url,使用普通的http请求和使用Ajax请求时,在请求头里有一个字段不同。

Ajax请求


普通http请求


可见如果 Ajax请求,请求头中多了一个字段X-Requested-With:XMLHttpRequest

通过这个字段阻止跨域请求。

JSONP是一种跨域交换协议,具体介绍网上很多,这里记录一个例子

<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><htmlxmlns="http://www.w3.org/1999/xhtml"><head><title>UntitledPage</title><scripttype="text/javascript"src="http://apps.bdimg.com/libs/jquery/1.9.1/jquery.min.js"></script><scripttype="text/javascript">jQuery(document).ready(function(){$.ajax({type:"get",async:false,url:"http://localhost/jquery-autocomplete/demo/json.php",dataType:"jsonp",jsonp:"callback",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(一般默认为:callback)jsonpCallback:"flightHandler",//自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名,也可以写"?",jQuery会自动为你处理数据success:function(result){alert(result.employees.length);},error:function(){alert('fail');}});});</script></head><body></body></html>

后端json.php

<?php$callback=$_GET['callback'];$result="{\"employees\":[{\"firstName\":\"Bill\",\"lastName\":\"Gates\"},{\"firstName\":\"George\",\"lastName\":\"Bush\"}]}";echo$callback."($result)";?>

浏览器请求http://localhost/jquery-autocomplete/demo/json.php?callback=flightHandler

返回的数据为

flightHandler({"employees":[{"firstName":"Bill","lastName":"Gates"},{"firstName":"George","lastName":"Bush"},{"firstName":"Thomas","lastName":"Carter"}]})

浏览器端弹出alert提示,跨域请求成功。