跨域访问一直是困扰很多开发者的问题之一。因为涉及到安全性问题,所以跨域访问默认是不可以进行的,否则假设今天我写了一段js去更改google的图标,明天他写了一段代码去吧google首页的文字全部变成梵文,那还得了?

首先,讲下什么是相同的域。域是这样定义的,协议名+host名+端口号,只有这3个都一样,才能说是同样的域,同样的域里面的访问不受到同源策略限制,你可以用你的js代码任意的去操作资源,但是不同域你就不能这样做了。

解决跨域访问有很多方法,最常见的一种“单向”跨域访问方式是用JSONP(Json with Padding),它解决思路就是如果域A (充当客户端)上的js 要操作域B(充当服务器端)上的资源,那么只要吧域A上的js函数名传递给域B,然后在域B进行封装,它解析来自域A的函数名,并且将域B上的资源转为json对象,并且两者进行组合,组合后的字符串就是 域A函数名(域B json对象)这种函数调用的形式,然后当域A上用script src=""的形式访问时,它拿到的结果就是一段js代码,并且是域A函数名(域B json对象)的形式,于是就达到了域A函数处理域B资源的效果。

为了更有说服力,我们这里做一个非常简单的实验,假定域A(客户端)有个应用部署在http://localhost:8180上,域B(服务器端)有个应用部署在http://localhost:8080上,显然这2个域由于端口不同,所以域A如果要访问域B必定是跨域访问的。域A 有一段js函数,域B提供了一个json对象,我们想要域A的js函数操作域B的json对象。会怎样呢?

服务端(我们部署在http://localhost:8080上):

先贴上域B(服务器端的代码),它用一个java servlet,负责接收来自客户端的带回调函数名参数的请求,并且与自己端提供的json对象包装,包装为一个jsonp后然后放入响应输出流。

packagecom.charles.jsonp;
importjava.io.IOException;
importjava.io.PrintWriter;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importorg.json.simple.JSONObject;
/**
* Servlet implementation class JSONPServlet
*/
publicclassJSONPServletextendsHttpServlet {
privatestaticfinallongserialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
publicJSONPServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protectedvoiddoGet(HttpServletRequest request, HttpServletResponse response)throwsServletException, IOException {
// TODO Auto-generated method stub
//get the callback function which comes from client
String callbackFuncFromClient= request.getParameter("callbackFunc");
//create a json object
JSONObject jsonInfo = newJSONObject();
jsonInfo.put("name","charles");
jsonInfo.put("title","technical lead");
jsonInfo.put("info","talent man");
//create a string which stands for a javascript with the format func(jsonobject)
StringBuffer jsonpString = newStringBuffer();
jsonpString.append(callbackFuncFromClient).append("(").append(jsonInfo.toJSONString()).append(")");
//construct the output jsonp and output to the client
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
out.println(jsonpString);
out.flush();
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protectedvoiddoPost(HttpServletRequest request, HttpServletResponse response)throwsServletException, IOException {
// TODO Auto-generated method stub
}
}

然后我们把这个servlet映射到某个url上,见web.xml:

This servlet will create a jsonp object,it wraps the js function and the json object
JSONPServlet
JSONPServlet
com.charles.jsonp.JSONPServlet
JSONPServlet
/JSONPServlet

现在我们测试服务器端是否已经正确部署:

我们打开浏览器,输入访问服务器端这个servlet的url,注意带上请求参数,参数名为callbackFunc,参数值为任意函数名:则我们可以看到封装后的JSONP效果,的确是“函数名(json对象)”的字符串形式。比如我们例子中,我们传入的函数名是 someFunc ,而服务器端自身提供的json对象是{"title":"technical lead","name":"charles","info":"talent man"},则最后服务器端返回的JSONP 字符串是someFunc{json}

html5跨域请求人家接口 html5新增的跨域解决方案_json对象

客户端:

服务器端部署正确后,我们让客户端部署在另外一个域:http://localhost:8180上,要实现跨域访问,客户端必须有2部分,1是定义一个回调函数(这个函数用于将来处理服务器json数据),二是一个页面,这个页面要用

这个回调函数能在控制台和alert窗口打印出服务器端的json对象提供的信息

//这段代码用于定义回调函数
functionclientMethodWhichOperateServerResource(result){
console.log("Begin to execute the call function named clientMethodWhichOperateServerResource(result)");
//获取服务器端传递过来的json字符串,转为json对象
varjsonObject=result;
//从json对象中分离出一些相关信息
varname=jsonObject.name;
vartitle=jsonObject.title;
varinfo=jsonObject.info;
console.log("name: "+name);
console.log("title: "+title);
console.log("info: "+info);
varserverInfoString="姓名: "+name+",";
serverInfoString+="头衔: "+title+",";
serverInfoString+="信息: "+info;
alert(serverInfoString);
}

然后我们定义一个页面:

这个页面的关键之处在于两段

<%@ pagelanguage="java"contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

这个页面用于演示JSONP


这个JSONP的例子的要点是,它用定义在客户端的一段js代码,去处理服务器上的json资源