导语:
在实际开发中,经常会调用一些其他域上提供的数据,其格式大部分为json格式的数据,怎么解决这种跨域问题呢,web前端开发工程师在面试中是经常会被问到的。因此特做一个小Demo以供大家参考。
一、在外域的服务器上创建一个服务器端的文件(以asp.net开发为例)
创建一个一般处理程序json.ashx:
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write("accepJson([{id:1,name:'孙文',age:432},{id:2,name:'李世民',age:632},{id:3,name:'乾隆',age:232},{id:4,name:'忽必烈',age:232},{id:5,name:'袁世凯',age:132}])");
}
向输出流中一定要输出一个双方约定好Js的函数accepJson(obj),这样在页面中引入此页面中,就会向页面中输出此函数的调用。如果在主页面中定义好此函数,当页面执行到引入处时就会调用此函数了,就实现了跨域的目的。
二、在本地创建一个html文件jsonp.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">
<head>
<title>本地文件</title>
<script type="text/javascript">
function accepJson(json) {
for (var i = 0; i < json.length; i++) {
//每个人的信息
var person = json[i];
//获得表格
var table = document.getElementById("tbPerson");
//插入tr
var tr = table.insertRow(-1);
//tr中插入td
var td1 = tr.insertCell(-1);
td1.innerHTML = person.id;
var td2 = tr.insertCell(-1);
td2.innerHTML = person.name;
var td3 = tr.insertCell(-1);
td3.innerHTML = person.age;
}
}
</script>
</head>
<body>
<table border="1" cellpadding="0" cellspacing="0" id="tbPerson">
</table>
<script type="text/javascript" src="http://192.168.1.101:32768/json.ashx"></script>
</body>
</html>
因为在该页面中已定义了accepJson(),因此当页面执行到<script type="text/javascript" src="http://192.168.1.101:32768/json.ashx"></script>时就可以调用该函数了,如果页面中没有此函数的定义,页面就会没有反应。
jquery方式实现跨域:
<!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">
<head>
<title>本地文件</title>
</head>
<body>
<table border="1" cellpadding="0" cellspacing="0" id="tbPerson">
</table>
<script src="../js/jquery-2.1.1.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
$.ajax({
type:"get",
url:"http://localhost:4481/%E8%B7%A8%E5%9F%9F/json.ashx",
dataType:'jsonp',
jsonp:'accepJson',
jsonpCallback:'accepJson',
async:true,
success:function(json){
//获得表格
var table = document.getElementById("tbPerson");
for (var i = 0; i < json.length; i++) {
//每个人的信息
var person = json[i];
//插入tr
var tr = table.insertRow(-1);
//tr中插入td
var td1 = tr.insertCell(-1);
td1.innerHTML = person.id;
var td2 = tr.insertCell(-1);
td2.innerHTML = person.name;
var td3 = tr.insertCell(-1);
td3.innerHTML = person.age;
}
}
});
</script>
</body>
</html>
jsonpCallback参数是服务器端返回的函数名即abc({"name":"郭老师"})中的“abc”是与服务器端约定好,让其下送回来的函数名称。
jsonp和jsonpCallback一个是上送回调函数名称,一个是下送执行函数名称。如果用jquery跨域,这两个参数都要设置。type必须为get请求!!!