jsonp的详解
1.jsonp是什么
jsonp(JSON with Padding)是json的一种‘使用模式’,可以让物业从别的域名(网站)那获取资料,即跨域读取数据。
2.jsonp的原理
ajax请求受同源策略影响,不允许进行跨域请求。而script标签src属性中的链接却可以访问跨域的js脚本,利用这个特性不再返回json格式数据,而是返回一段调用某一个函数的js代码,在src中进行了调用,这样实现了跨域。
3.jsonp的应用
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JSONP 实例</title>
</head>
<body>
<div id="divCustomers"></div>
<script type="text/javascript">
function callbackFunction(result, methodName)
</script><script type="text/javascript" src="http://www.runoob.com/try/ajax/jsonp.php?jsoncallback=callbackFunction">
{ var html = '<ul>';
for(var i = 0; i < result.length; i++)
{ html += '<li>' + result[i] + '</li>';
}
html += '</ul>';
document.getElementById('divCustomers').innerHTML = html;
}
</script></body></html>
4.jsonp的在其他框架的使用
在jquery的应用:
$.ajax({
type : "get",
async: false,
url : "http://www.practice-zhao.com/student.php?id=1",
dataType: "jsonp",
jsonp:"callback", //请求php的参数名
jsonpCallback: "jsonhandle",//要执行的回调函数
success : function(data) {
alert("age:" + data.age + "name:" + data.name);
}
});