浏览器安全策略:
首先我们先来了解一下所谓的“浏览器安全策略“。
浏览器安全策略:如果从某一个域获取页面本身,该安全策略要求不能从另一个域获取数据。比如说我从小明那拿到了页面,但我现在想去小华那里拿数据,这样是不允许的。那怎么解决这个问题呢?
答案就是我们要介绍的jsonp:
jsonp:是一种通过使用<script>标记获取json对象的方法。它可以解决XMLHttpRequest同源安全 的问题。
下面我们通过代码来解释吧:
实例代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title><pre name="code" class="html">jsonp简单教程</title>
</head>
<body>
<div id="divCustomers"></div>
<script type="text/javascript">
function callbackFunction(result) {
var html = '<ol>';
for(var i = 0; i < result.length; i++) {
html += '<li>' + result[i] + '</li>';
}
html += '</ul>';
document.getElementById('divCustomers').innerHTML = html;
}
</script>
<script type="text/javascript" src="http://localhost:8080/javaWebStudy1/json.php?jsoncallback=callbackFunction"></script>//callackFunction为回调函数,;在这里要强调的是每次创建<script>都会使浏览器做出一次请求。
</body>
</html>
服务端代码:json.php如下
<?php header('Content-type: application/json'); //获取回调函数名 $jsoncallback = htmlspecialchars($_REQUEST ['jsoncallback']); //json数据 $json_data = '["customername1","customername2"]'; //输出jsonp格式的数据 echo $jsoncallback . "(" . $json_data . ")"; ?>
JQuery Ajax 跨域请求实例:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>使用jQuery-AJAX--读取获得跨域JSONP数据</title>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js" type="text/javascript"></script>
</head>
<body>
<h2><a href="javascript:void(0)" class="btnAJAX">点击AJAX获取数据JSONP跨域....</a></h2>
<script type="text/javascript">
$(function() {
$(".btnAJAX").click(function(){
$.ajax({
type : "get",
async:true,
url : "http://weather.123.duba.net/static/weather_info/101121301.html",
dataType : "jsonp",
jsonp: "callbackparam", //服务端用于接收callback调用的function名的参数
jsonpCallback:"weather_callback", //callback的function名称
success : function(json){
// console.log(json); //浏览器调试的时候用
alert(json.weatherinfo.city);
alert(json.weatherinfo.week);
alert(json.update_time);
alert(json.weatherinfo.fl1);
},
error:function(){
alert('fail');
}
});
});
});
</script>
</body>
</html>
php 跨域解决方案:http://www.runoob.com/w3cnote/php-ajax-cross-border.html